@xeokit/xeokit-sdk 2.6.86 → 2.6.87
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 +10 -9
- package/dist/xeokit-sdk.es.js +10 -9
- package/dist/xeokit-sdk.es5.js +5 -5
- package/dist/xeokit-sdk.min.cjs.js +4 -4
- package/dist/xeokit-sdk.min.es.js +4 -4
- package/dist/xeokit-sdk.min.es5.js +4 -4
- package/package.json +1 -1
- package/src/viewer/scene/CameraControl/lib/handlers/TouchPickHandler.js +7 -6
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* xeokit-sdk v2.6.
|
|
3
|
-
* Commit:
|
|
4
|
-
* Built: 2025-07-
|
|
2
|
+
* xeokit-sdk v2.6.87
|
|
3
|
+
* Commit: 8fcdaeda55a3bd75b49a6cc6fe5d950fa3251f38
|
|
4
|
+
* Built: 2025-07-31T17:46:22.388Z
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
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 o{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 o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i<o;i++){const o=e[i],a=new s;n.groups.push(a);for(let e=0,i=o.length;e<i;e++){const i=o[e],s=i.items,l=s&&s.length>0,A=this._getNextId(),c=i.getTitle||(()=>i.title||""),h=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,c,h,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};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,o=s,n=t[e].items;if(n)for(let e=0,t=n.length;e<t;e++){const s=n[e],a=s.subMenu,l=s.title||"";a?(i.push('<li id="'+s.id+'" class="xeokit-context-menu-item xeokit-context-menu-submenu">'+l+"</li>"),r===o-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">'+l+"</li>"),r===o-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 o=this;let n=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(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();const l=o._offsetParent.getBoundingClientRect(),A=200,c=a.right+A<l.right,h=a.left-A>l.left;if(c)o._showMenu(i.id,a.right+window.scrollX-5,a.top+window.scrollY-1);else if(h)o._showMenu(i.id,a.left-A+window.scrollX,a.top+window.scrollY-1);else{const e=a.left-l.left,t=l.right-a.right;t>e?o._showMenu(i.id,a.right-5-(A-t),a.top+window.scrollY-1):o._showMenu(i.id,a.left-e,a.top+window.scrollY-1)}n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._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 o=r(this._context);if(t.shown=o,!o){i.style.display="none";continue}i.style.display="";const n=s(this._context);t.enabled=n,n?i.classList.remove("disabled"):i.classList.add("disabled")}}_updateSubMenuInfo(){if(!this._context)return;let e,t,i,s,r,o;this._itemList.forEach((n=>{n.subMenu&&(e=n.itemElement,t=e.getBoundingClientRect(),i=n.subMenu.menuElement,s={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",o=n.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=s.visibility,i.style.display=s.display,r=t.right+o>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,o=this._offsetParent.getBoundingClientRect(),n=this._offsetParent===window.document.body&&0===o.bottom?window.innerHeight:o.bottom+window.scrollY,a=o.right+window.scrollX;i+s>n&&(i=n-s),t+r>a&&(t=a-r),e.style.left=t-o.left-window.scrollX+"px",e.style.top=i-o.top-window.scrollY+"px"}_hideMenuElement(e){e.style.display="none"}}class n{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,o=this._snappedCanvasPos?this._snappedCanvasPos[0]-this._canvasPos[0]:0,n=this._snappedCanvasPos?this._snappedCanvasPos[1]-this._canvasPos[1]:0;this._lensCursorDiv.style.left=`${r+o*this._zoomLevel}px`,this._lensCursorDiv.style.top=`${r+n*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 a=!0,l=a?Float64Array:Float32Array;const A=new l(3),c=new l(16),h=new l(16),u=new l(4),d={setDoublePrecisionEnabled(e){a=e,l=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,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 l(e||2),vec3:e=>new l(e||3),vec4:e=>new l(e||4),mat3:e=>new l(e||9),mat3ToMat4:(e,t=new l(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 l(e||16),mat4ToMat3:(e,t=new l(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 l(2);for(let r=0,o=e.length;r<o;r++)d.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble(e,t){const i=l.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 l(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],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,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 l(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new l(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 l(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 l([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 l(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 l(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],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],_=e[15],v=t[0],b=t[1],y=t[2],w=t[3],B=t[4],P=t[5],x=t[6],C=t[7],M=t[8],E=t[9],F=t[10],I=t[11],T=t[12],D=t[13],S=t[14],R=t[15];return i[0]=v*s+b*a+y*h+w*f,i[1]=v*r+b*l+y*u+w*m,i[2]=v*o+b*A+y*d+w*g,i[3]=v*n+b*c+y*p+w*_,i[4]=B*s+P*a+x*h+C*f,i[5]=B*r+P*l+x*u+C*m,i[6]=B*o+P*A+x*d+C*g,i[7]=B*n+P*c+x*p+C*_,i[8]=M*s+E*a+F*h+I*f,i[9]=M*r+E*l+F*u+I*m,i[10]=M*o+E*A+F*d+I*g,i[11]=M*n+E*c+F*p+I*_,i[12]=T*s+D*a+S*h+R*f,i[13]=T*r+D*l+S*u+R*m,i[14]=T*o+D*A+S*d+R*g,i[15]=T*n+D*c+S*p+R*_,i},mulMat3(e,t,i){i||(i=new l(9));const s=e[0],r=e[3],o=e[6],n=e[1],a=e[4],A=e[7],c=e[2],h=e[5],u=e[8],d=t[0],p=t[3],f=t[6],m=t[1],g=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*m+o*v,i[3]=s*p+r*g+o*b,i[6]=s*f+r*_+o*y,i[1]=n*d+a*m+A*v,i[4]=n*p+a*g+A*b,i[7]=n*f+a*_+A*y,i[2]=c*d+h*m+u*v,i[5]=c*p+h*g+u*b,i[8]=c*f+h*_+u*y,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],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],c=e[6],h=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=s,e[12]=A,e[13]=h,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,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],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],c=e[9],h=e[10],u=e[11],d=e[12],p=e[13],f=e[14],m=e[15];return d*c*a*r-A*p*a*r-d*n*h*r+o*p*h*r+A*n*f*r-o*c*f*r-d*c*s*l+A*p*s*l+d*i*h*l-t*p*h*l-A*i*f*l+t*c*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*m+o*c*s*m+A*i*a*m-t*c*a*m-o*i*h*m+t*n*h*m},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],c=e[8],h=e[9],u=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,w=s*A-o*a,B=r*A-o*l,P=c*f-h*p,x=c*m-u*p,C=c*g-d*p,M=h*m-u*f,E=h*g-d*f,F=u*g-d*m,I=1/(_*F-v*E+b*M+y*C-w*x+B*P);return t[0]=(a*F-l*E+A*M)*I,t[1]=(-s*F+r*E-o*M)*I,t[2]=(f*B-m*w+g*y)*I,t[3]=(-h*B+u*w-d*y)*I,t[4]=(-n*F+l*C-A*x)*I,t[5]=(i*F-r*C+o*x)*I,t[6]=(-p*B+m*b-g*v)*I,t[7]=(c*B-u*b+d*v)*I,t[8]=(n*E-a*C+A*P)*I,t[9]=(-i*E+s*C-o*P)*I,t[10]=(p*w-f*b+g*_)*I,t[11]=(-c*w+h*b-d*_)*I,t[12]=(-n*M+a*x-l*P)*I,t[13]=(i*M-s*x+r*P)*I,t[14]=(-p*y+f*v-m*_)*I,t[15]=(c*y-h*v+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 l(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 o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*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),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let c,h,u,p,f,m;return c=a*l,h=l*A,u=A*a,p=a*r,f=l*r,m=A*r,(i=i||d.mat4())[0]=n*a*a+o,i[1]=n*c+m,i[2]=n*u-f,i[3]=0,i[4]=n*c-m,i[5]=n*l*l+o,i[6]=n*h+p,i[7]=0,i[8]=n*u+f,i[9]=n*h-p,i[10]=n*A*A+o,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 l(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],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,c=s*a,h=s*l,u=s*A,p=r*l,f=r*A,m=o*A,g=n*a,_=n*l,v=n*A;return i[0]=1-(p+m),i[1]=h+v,i[2]=u-_,i[3]=0,i[4]=h-v,i[5]=1-(c+m),i[6]=f+g,i[7]=0,i[8]=u+_,i[9]=f-g,i[10]=1-(c+p),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],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],c=e[2],h=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(h,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,u),i[2]=Math.atan2(a,l)):(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(-o,l)):(i[1]=0,i[2]=Math.atan2(a,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(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(n,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(h,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,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 l(3),t=new l(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=d.lenVec3(e);d.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,c=1/a,h=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=h,t[9]*=h,t[10]*=h,d.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,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],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],c=t[0],h=t[1],u=t[2];if(r===c&&o===h&&n===u)return d.identityMat4();let p,f,m,g,_,v,b,y,w,B;return p=r-c,f=o-h,m=n-u,B=1/Math.sqrt(p*p+f*f+m*m),p*=B,f*=B,m*=B,g=l*m-A*f,_=A*p-a*m,v=a*f-l*p,B=Math.sqrt(g*g+_*_+v*v),B?(B=1/B,g*=B,_*=B,v*=B):(g=0,_=0,v=0),b=f*v-m*_,y=m*g-p*v,w=p*_-f*g,B=Math.sqrt(b*b+y*y+w*w),B?(B=1/B,b*=B,y*=B,w*=B):(b=0,y=0,w=0),s[0]=g,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=w,s[10]=m,s[11]=0,s[12]=-(g*r+_*o+v*n),s[13]=-(b*r+y*o+w*n),s[14]=-(p*r+f*o+m*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>d.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},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 o=2*s[2],n=h[0],a=h[1],l=h[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=c[0]/n,i[9]=c[1]/a,i[10]=-c[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],d.frustumMat4v(o,n,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],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+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 o,n,a,l;const A=e[0],c=e[1],h=e[2],u=e[3],d=e[4],p=e[5],f=e[6],m=e[7],g=e[8],_=e[9],v=e[10],b=e[11],y=e[12],w=e[13],B=e[14],P=e[15];let x;for(let e=0;e<r;++e)l=t[e],o=l[0],n=l[1],a=l[2],x=s[e]||(s[e]=[0,0,0]),x[0]=A*o+d*n+g*a+y,x[1]=c*o+p*n+_*a+w,x[2]=h*o+f*n+v*a+B,x[3]=u*o+m*n+b*a+P;return s.length=r,s},transformPositions3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2];e[3];const h=e[4],u=e[5],d=e[6];e[7];const p=e[8],f=e[9],m=e[10];e[11];const g=e[12],_=e[13],v=e[14];for(e[15],s=0;s<r;s+=3)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+h*n+p*a+g,i[s+1]=A*o+u*n+f*a+_,i[s+2]=c*o+d*n+m*a+v;return i},transformPositions4(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2],h=e[3],u=e[4],d=e[5],p=e[6],f=e[7],m=e[8],g=e[9],_=e[10],v=e[11],b=e[12],y=e[13],w=e[14],B=e[15];for(s=0;s<r;s+=4)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+u*n+m*a+b,i[s+1]=A*o+d*n+g*a+y,i[s+2]=c*o+p*n+_*a+w,i[s+3]=h*o+f*n+v*a+B;return i},transformVec3(e,t,i){const s=t[0],r=t[1],o=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*o,i[1]=e[1]*s+e[5]*r+e[9]*o,i[2]=e[2]*s+e[6]*r+e[10]*o,i},transformVec4(e,t,i){const s=t[0],r=t[1],o=t[2],n=t[3];return(i=i||d.vec4())[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},rotateVec2(e,t,i,s=e){const r=Math.cos(i),o=Math.sin(i),n=e[0]-t[0],a=e[1]-t[1];return s[0]=n*r-a*o+t[0],s[1]=n*o+a*r+t[1],e},rotateVec3X(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0],o[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),o[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Y(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),o[1]=r[1],o[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Z(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),o[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),o[2]=r[2],s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[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 l(16),t=new l(16),i=new l(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||d.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||d.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i<s;i++)for(n=e[i],r=0,o=n.length;r<o;r++)t.push(n[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,o=e[2]*d.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),c=Math.sin(r),h=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*c*h,i[1]=n*c*l-A*a*h,i[2]=n*a*h+A*c*l,i[3]=n*a*l-A*c*h):"YXZ"===t?(i[0]=A*a*l+n*c*h,i[1]=n*c*l-A*a*h,i[2]=n*a*h-A*c*l,i[3]=n*a*l+A*c*h):"ZXY"===t?(i[0]=A*a*l-n*c*h,i[1]=n*c*l+A*a*h,i[2]=n*a*h+A*c*l,i[3]=n*a*l-A*c*h):"ZYX"===t?(i[0]=A*a*l-n*c*h,i[1]=n*c*l+A*a*h,i[2]=n*a*h-A*c*l,i[3]=n*a*l+A*c*h):"YZX"===t?(i[0]=A*a*l+n*c*h,i[1]=n*c*l+A*a*h,i[2]=n*a*h-A*c*l,i[3]=n*a*l-A*c*h):"XZY"===t&&(i[0]=A*a*l-n*c*h,i[1]=n*c*l-A*a*h,i[2]=n*a*h+A*c*l,i[3]=n*a*l+A*c*h),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],c=e[10];let h;const u=i+n+c;return u>0?(h=.5/Math.sqrt(u+1),t[3]=.25/h,t[0]=(A-a)*h,t[1]=(r-l)*h,t[2]=(o-s)*h):i>n&&i>c?(h=2*Math.sqrt(1+i-n-c),t[3]=(A-a)/h,t[0]=.25*h,t[1]=(s+o)/h,t[2]=(r+l)/h):n>c?(h=2*Math.sqrt(1+n-i-c),t[3]=(r-l)/h,t[0]=(s+o)/h,t[1]=.25*h,t[2]=(a+A)/h):(h=2*Math.sqrt(1+c-i-n),t[3]=(o-s)/h,t[0]=(r+l)/h,t[1]=(a+A)/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 l(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],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],c=t[3];return i[0]=n*a+s*c+r*A-o*l,i[1]=n*l+r*c+o*a-s*A,i[2]=n*A+o*c+s*l-r*a,i[3]=n*c-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],c=A*s+a*o-l*r,h=A*r+l*s-n*o,u=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=c*A+p*-n+h*-l-u*-a,i[1]=h*A+p*-a+u*-n-c*-l,i[2]=u*A+p*-l+c*-a-h*-n,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,c=a*o,h=l*o,u=n*i,p=a*i,f=l*i,m=a*s,g=l*s,_=l*r;return t[0]=1-(m+_),t[1]=p+h,t[2]=f-c,t[4]=p-h,t[5]=1-(u+_),t[6]=g+A,t[8]=f+c,t[9]=g-A,t[10]=1-(u+m),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,c=i*a,h=i*l,u=s*a,d=s*l,p=r*l,f=o*n,m=o*a,g=o*l;return t[0]=1-(u+p),t[4]=c-g,t[8]=h+m,t[1]=c+g,t[5]=1-(A+p),t[9]=d-f,t[2]=h-m,t[6]=d+f,t[10]=1-(A+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 l(e||6),AABB2:e=>new l(e||4),OBB3:e=>new l(e||32),OBB2:e=>new l(e||16),Sphere3:(e,t,i,s)=>new l([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2],h=e[3],u=e[4],d=e[5],p=e[6],f=e[7],m=e[8],g=e[9],_=e[10],v=e[11],b=e[12],y=e[13],w=e[14],B=e[15];for(s=0;s<r;s+=4)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+u*n+m*a+b,i[s+1]=A*o+d*n+g*a+y,i[s+2]=c*o+p*n+_*a+w,i[s+3]=h*o+f*n+v*a+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 l(3),t=new l(3),i=new l(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 l(3),t=new l(3),i=new l(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 o=d.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],c=r[2]-s[2],h=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=c>h?c:h,Math.abs(d.lenVec3(o))}})(),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 l(3);return(t,i,s)=>{i=i||d.AABB3();let r,o,n,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,A=d.MAX_DOUBLE,c=d.MIN_DOUBLE,h=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,p=t.length;i<p;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],o=e[1],n=e[2]):(r=t[i+0],o=t[i+1],n=t[i+2]),r<a&&(a=r),o<l&&(l=o),n<A&&(A=n),r>c&&(c=r),o>h&&(h=o),n>u&&(u=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=c,i[4]=h,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=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<o&&(o=i),s<n&&(n=s),r<a&&(a=r),i>l&&(l=i),s>A&&(A=s),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=c,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=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<o&&(o=i),s<n&&(n=s),r<a&&(a=r),i>l&&(l=i),s>A&&(A=s),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=c,t},points3ToSphere3:(()=>{const e=new l(3);return(t,i)=>{i=i||d.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;s<a;s++)r+=t[s][0],o+=t[s][1],n+=t[s][2];i[0]=r/a,i[1]=o/a,i[2]=n/a;let l,A=0;for(s=0;s<a;s++)l=Math.abs(d.lenVec3(d.subVec3(t[s],i,e))),l>A&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;r<l;r+=3)o+=i[r],n+=i[r+1],a+=i[r+2];const c=l/3;let h;for(s[0]=o/c,s[1]=n/c,s[2]=a/c,r=0;r<l;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>A&&(A=h);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;r<l;r+=4)o+=i[r+0],n+=i[r+1],a+=i[r+2];s[0]=o/A,s[1]=n/A,s[2]=a/A;let c,h=0;for(r=0;r<l;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 o=0,n=e.length;o<n;o+=3)i+=e[o+0],s+=e[o+1],r+=e[o+2];const a=e.length/3;return t[0]=i/a,t[1]=s/a,t[2]=r/a,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,o=0,n=t.length;o<n;o+=3)i=t[o],s=t[o+1],r=t[o+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,o,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=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,o=1/r,i*=o,s*=o,i<n&&(n=i),s<a&&(a=s),i>l&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,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),o=.5*(e[1]+1),n=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(n*t),s[3]=i-Math.floor(o*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 o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*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],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],c=o*A-n*l,h=n*a-r*A,u=r*l-o*a,p=Math.sqrt(c*c+h*h+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/p,s[1]=h/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3);return(o,n,a,l,A,c)=>{c=c||d.vec3();const h=d.subVec3(l,a,e),u=d.subVec3(A,a,t),p=d.cross3Vec3(n,u,i),f=d.dotVec3(h,p);if(f<1e-6)return null;const m=d.subVec3(o,a,s),g=d.dotVec3(m,p);if(g<0||g>f)return null;const _=d.cross3Vec3(m,h,r),v=d.dotVec3(n,_);if(v<0||g+v>f)return null;const b=d.dotVec3(u,_)/f;return c[0]=o[0]+b*n[0],c[1]=o[1]+b*n[1],c[2]=o[2]+b*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3);return(r,o,n,a,l,A)=>{A=A||d.vec3(),o=d.normalizeVec3(o,e);const c=d.subVec3(a,n,t),h=d.subVec3(l,n,i),u=d.cross3Vec3(c,h,s);d.normalizeVec3(u,u);const p=-d.dotVec3(n,u),f=-(d.dotVec3(r,u)+p)/d.dotVec3(o,u);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r,o,n,a)=>{const l=d.subVec3(n,r,e),A=d.subVec3(o,r,t),c=d.subVec3(s,r,i),h=d.dotVec3(l,l),u=d.dotVec3(l,A),p=d.dotVec3(l,c),f=d.dotVec3(A,A),m=d.dotVec3(A,c),g=h*f-u*u;if(0===g)return null;const _=1/g,v=(f*p-u*m)*_,b=(h*m-u*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),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 o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let c,h,u,d;const p=1e4;let f,m,g=0;for(f=0,m=e.length;f<m;f+=3)c=e[f],h=e[f+1],u=e[f+2],d=`${Math.round(c*p)}_${Math.round(h*p)}_${Math.round(u*p)}`,void 0===r[d]&&(r[d]=n.length/3,n.push(c),n.push(h),n.push(u),t&&(a.push(t[f]),a.push(t[f+1]),a.push(t[f+2])),i&&(l.push(i[g]),l.push(i[g+1]))),o[f/3]=r[d],g+=2;for(f=0,m=s.length;f<m;f++)A[f]=o[s[f]];const _={positions:n,indices:A};return a&&(_.normals=a),l&&(_.uv=l),_},buildNormals:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let A,c;const h=new Array(n.length/3);let u,p,f,m,g,_,v;for(A=0,c=a.length;A<c;A+=3){u=a[A],p=a[A+1],f=a[A+2],e[0]=n[3*u],e[1]=n[3*u+1],e[2]=n[3*u+2],t[0]=n[3*p],t[1]=n[3*p+1],t[2]=n[3*p+2],i[0]=n[3*f],i[1]=n[3*f+1],i[2]=n[3*f+2],d.subVec3(t,e,s),d.subVec3(i,e,r);const l=d.vec3();d.normalizeVec3(d.cross3Vec3(s,r,o),l),h[u]||(h[u]=[]),h[p]||(h[p]=[]),h[f]||(h[f]=[]),h[u].push(l),h[p].push(l),h[f].push(l)}for(l=l&&l.length===n.length?l:new Float32Array(n.length),A=0,c=h.length;A<c;A++){m=h[A].length,g=0,_=0,v=0;for(let e=0;e<m;e++)g+=h[A][e][0],_+=h[A][e][1],v+=h[A][e][2];l[3*A]=g/m,l[3*A+1]=_/m,l[3*A+2]=v/m}return l}})(),buildTangents:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,A)=>{const c=new Float32Array(a.length);for(let h=0;h<l.length;h+=3){let u=l[h];const p=a.subarray(3*u,3*u+3),f=A.subarray(2*u,2*u+2);u=l[h+1];const m=a.subarray(3*u,3*u+3),g=A.subarray(2*u,2*u+2);u=l[h+2];const _=a.subarray(3*u,3*u+3),v=A.subarray(2*u,2*u+2),b=d.subVec3(m,p,e),y=d.subVec3(_,p,t),w=d.subVec2(g,f,i),B=d.subVec2(v,f,s),P=1/(w[0]*B[1]-w[1]*B[0]),x=d.mulVec3Scalar(d.subVec3(d.mulVec3Scalar(b,B[1],r),d.mulVec3Scalar(y,w[1],o),n),P,o);let C;for(let e=0;e<3;e++)C=3*l[h+e],c[C]+=x[0],c[C+1]+=x[1],c[C+2]+=x[2]}return c}})(),buildPickTriangles(e,t,i){const s=t.length,r=i?new Uint16Array(9*s):new Float32Array(9*s),o=new Uint8Array(12*s);let n,a,l,A,c,h,u=0,d=0,p=0;for(let i=0;i<s;i+=3)h=u>>24&255,c=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,c,h;const u=1e4;let p,f,m,g,_,v;for(f=0,g=e.length;f<g;f+=3){p=f/3,l=e[f],A=e[f+1],c=e[f+2],h=`${Math.round(l*u)}_${Math.round(A*u)}_${Math.round(c*u)}`,void 0===r[h]?r[h]=[p]:r[h].push(p);const i=d.normalizeVec3([t[f],t[f+1],t[f+2]]);o[p]=i,a=d.vec4([i[0],i[1],i[2],1]),n[p]=a}for(h in r)if(r.hasOwnProperty(h)){const e=r[h],t=e.length;for(f=0;f<t;f++){const i=e[f];for(a=n[i],m=0;m<t;m++){if(f===m)continue;const t=e[m];_=o[i],v=o[t];Math.abs(d.angleVec3(_,v)/d.DEGTORAD)<s&&(a[0]+=v[0],a[1]+=v[1],a[2]+=v[2],a[3]+=1)}}}for(f=0,g=t.length;f<g;f+=3)a=n[f/3],t[f+0]=a[0]/a[3],t[f+1]=a[1]/a[3],t[f+2]=a[2]/a[3]},transformRay:(()=>{const e=new l(4),t=new l(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(4),i=new l(4),s=(t,i,s,r,o)=>{o[0]=t,o[1]=i,o[2]=s,o[3]=1,d.transformVec4(e,o,o),r||d.mulVec4Scalar(o,1/o[3])};return(r,o,n,a,l,A,c)=>{const h="ortho"===a;d.mulMat4(n,o,e),d.inverseMat4(e,e);const u=2*l[0]/r.clientWidth-1,p=1-2*l[1]/r.clientHeight;s(u,p,-1,h,t),s(u,p,1,h,i),A[0]=t[0],A[1]=t[1],A[2]=t[2],d.subVec3(i,t,c),d.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(i,s,r,o,n,a,l,A)=>{d.canvasPosToWorldRay(i,s,r,o,a,e,t),d.worldRayToLocalRay(n,e,t,l,A)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),i=new l(4);return(s,r,o,n,a)=>{const l=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],d.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let A,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,A=0,c=i.length;A<c;++A){var h=3*i[A];for(let e=0;e<3;++e){const t=3*s[h+e];r[t]<n[0]&&(n[0]=r[t]),r[t]>n[3]&&(n[3]=r[t]),r[t+1]<n[1]&&(n[1]=r[t+1]),r[t+1]>n[4]&&(n[4]=r[t+1]),r[t+2]<n[2]&&(n[2]=r[t+2]),r[t+2]>n[5]&&(n[5]=r[t+2])}}if(i.length<20||o>10)return a.triangles=i,a.leaf=!0,a;e[0]=n[3]-n[0],e[1]=n[4]-n[1],e[2]=n[5]-n[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),a.splitDim=u;const d=(n[u]+n[u+3])/2,p=new Array(i.length);let f=0;const m=new Array(i.length);let g=0;for(A=0,c=i.length;A<c;++A){const e=s[h=3*i[A]],t=3*s[h+1],o=3*s[h+2];r[3*e+u]<=d||r[t+u]<=d||r[o+u]<=d?p[f++]=i[A]:m[g++]=i[A]}return p.length=f,m.length=g,a.left=t(p,s,r,o+1),a.right=t(m,s,r,o+1),a}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 o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const n=1-Math.abs(r)-Math.abs(o);n<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),m=d.vec3();return function(g,_,v,b){!function(r,o){const n={};let a,l,A,c;const h=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;u<d;u+=3)a=r[u],l=r[u+1],A=r[u+2],c=Math.round(a*h)+"_"+Math.round(l*h)+"_"+Math.round(A*h),void 0===n[c]&&(n[c]=p/3,e[p++]=a,e[p++]=l,e[p++]=A),t[u/3]=n[c];for(u=0,d=o.length;u<d;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,_),function(t,i){o=0;for(let g=0,_=t;g<_;g+=3){const t=3*s[g],_=3*s[g+1],v=3*s[g+2];i?(n[0]=e[t],n[1]=e[t+1],n[2]=e[t+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],d.decompressPosition(n,i,A),d.decompressPosition(a,i,c),d.decompressPosition(l,i,h)):(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],h[0]=e[v],h[1]=e[v+1],h[2]=e[v+2]),d.subVec3(h,c,u),d.subVec3(A,c,p),d.cross3Vec3(u,p,f),d.normalizeVec3(f,m);const b=r[o]||(r[o]={normal:d.vec3()});b.normal[0]=m[0],b.normal[1]=m[1],b.normal[2]=m[2],o++}}(_.length,v);const y=[],w=Math.cos(d.DEGTORAD*b),B={};let P,x,C,M,E,F,I,T,D,S,R,U=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)P=s[e+i],x=s[e+(i+1)%3],C=Math.min(P,x),M=Math.max(P,x),E=C+","+M,void 0===B[E]?B[E]={index1:C,index2:M,face1:t,face2:void 0}:B[E].face2=t}for(E in B)F=B[E],void 0!==F.face2&&(I=r[F.face1].normal,T=r[F.face2].normal,D=d.dotVec3(I,T),D>w)||(S=i[F.index1],R=i[F.index2],(!U&&S>65535||R>65535)&&(U=!0),y.push(S),y.push(R));return U?new Uint32Array(y):new Uint16Array(y)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r<o;r+=s){if(A[0]=i[r+0]-e[0],A[1]=i[r+1]-e[1],A[2]=i[r+2]-e[2],A[0]*t[0]+A[1]*t[1]+A[2]*t[2]<0)return!0}return!1};const p=new Float32Array(3);class f{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;p[0]=r[3]-r[0],p[1]=r[4]-r[1],p[2]=r[5]-r[2];let o=0;if(p[1]>p[o]&&(o=1),p[2]>p[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},d.containsAABB3(n,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 m{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 g={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 v(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 b=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 y={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 o=0;o<t.attributes.length;o++){var n=t.attributes[o];r[i[n.nodeName]||n.nodeName]=n.nodeValue}for(var a=0;a<t.childNodes.length;a++){(o=e(t.childNodes[a],i))&&r.children.push(o)}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 v(t[0],2)+[1,4,7,10,13].map((function(e){return v((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 o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n<o.length;n++)i[n]=o.charCodeAt(n);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:b,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 y.isString(e)||y.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(y.isNumeric(e)||y.isString(e)?`${e}`:e.id)===(y.isNumeric(t)||y.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 y.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 y.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,o=s.length;r<o;r++){s[r].parent=i.id,e(s[r])}i.children=[]}(e),t}},w={},B=new e,P=new m,x={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},C=[];let M,E=0,F=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 ${y.inQuotes(e.id)} already exists`)}else e.id=B.addItem({});I.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;w[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},g.components.scenes++,e.once("destroyed",(()=>{B.removeItem(e.id),delete I.scenes[e.id],delete w[e.id],g.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){P.push(e),P.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;P.length>0&&(e<0||s<e);)t=P.shift(),i=P.shift(),i?t.call(i):t(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return P.length}},T=function(){let e=Date.now();if(M=e-E,E>0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),g.frame.fps=Math.round(F/C.length)}for(let e in I.scenes)I.scenes[e].compile();S(e),E=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 D=function(){let e=Date.now();if(M=e-E,E>0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),g.frame.fps=Math.round(F/C.length)}S(e),function(e){for(var t in x.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];x.sceneId=t,x.startTime=i.startTime,x.deltaTime=null!=x.prevTime?x.time-x.prevTime:0,i.fire("tick",x,!0)}x.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=w[n],s||(s=w[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(T):requestAnimationFrame(D)};function S(e){const t=I.runTasks(e+10),i=I.getNumTasks();g.frame.tasksRun=t,g.frame.tasksScheduled=i,g.frame.tasksBudget=10}D();class R{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 R))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 o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}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+" "+y.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,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(y.isNumeric(i)||y.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+y.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];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+" "+y.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+y.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,c,h;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,c=0,h=A.length;c<h;c++)l.off(A[c]);delete this._attached[t],delete this._attachments[l.id];const s=e.params.onDetached;s&&(y.isFunction(s)?s(l):s.scope?s.callback.call(s.scope,l):s.callback(l)),e.managingLifecycle&&l.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)),a&&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&&(y.isFunction(r)?r(i):r.scope?r.callback.call(r.scope,i):r.callback(i)),n){let e,t,r,o;for(e in n)if(n.hasOwnProperty(e)){if(t=n[e],y.isFunction(t)?(r=t,o=null):(r=t.callback,o=t.scope),!r)continue;s.subs.push(i.on(e,r,o))}}}return a&&this.fire("dirty",this),this.fire(t,i),i}_checkComponent(e,t){if(!t.isComponent){if(!y.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(!y.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,o;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,o=s.length;r<o;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 U=d.vec3(),L=d.vec3(),k=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 N{constructor(){this.planes=[new O,new O,new O,new O,new O,new O]}}function V(e,t,i){const s=d.mulMat4(i,t,k),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],c=s[6],h=s[7],u=s[8],p=s[9],f=s[10],m=s[11],g=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,h-l,m-u,b-g),e.planes[1].set(a+r,h+l,m+u,b+g),e.planes[2].set(a-o,h-A,m-p,b-_),e.planes[3].set(a+o,h+A,m+p,b+_),e.planes[4].set(a-n,h-c,m-f,b-v),e.planes[5].set(a+n,h+c,m+f,b+v)}function Q(e,t){let i=N.INSIDE;const s=U,r=L;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 o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return N.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=N.INTERSECT)}return i}N.INSIDE=0,N.INTERSECT=1,N.OUTSIDE=2;class H extends R{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 N,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!==H.PICK_MODE_INSIDE&&e!==H.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===H.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=N.INTERSECT)=>{if(s===N.INTERSECT&&(s=Q(this._marqueeFrustum,i.aabb)),s!==N.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===H.PICK_MODE_INSIDE){Q(this._marqueeFrustum,r)===N.INSIDE&&e.push(s.id)}else{Q(this._marqueeFrustum,r)!==N.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,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,c=-(this._canvasMarquee[3]-r)*n+1,h=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);d.frustumMat4(l,A,c*a,h*a,u,1e4,this._marqueeFrustumProjMat),V(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)}}H.PICK_MODE_INTERSECTS=0,H.PICK_MODE_INSIDE=1;class j extends R{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,c=!1,h=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=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(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);c=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),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(A),c&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a<l?H.PICK_MODE_INSIDE:H.PICK_MODE_INTERSECTS)))}))}setActive(e){this._active!==e&&(this._active=e,this.fire("active",this._active))}getActive(){return this._active}destroy(){}}class G{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,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,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",o<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 z{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=W(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=W(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 o=this._events[t];return void 0!==o&&i(o),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 W(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 R{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),o=this.getPoint(s),n=d.subVec3(o,r,[]);return d.normalizeVec3(n,[])}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),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=d.lenVec3(d.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-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,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=d.vec3();return A[0]=d.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=d.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=d.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}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 R{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,o=this._frames.length;e<o;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 q=d.vec3(),$=d.vec3(),ee=d.vec3(),te=d.vec3(),ie=d.vec3();class se extends R{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 o,n,a,l,A;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)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((y.isNumeric(s)||y.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+y.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const c=e.poi;if(o){if(o[3]<o[0]||o[4]<o[1]||o[5]<o[2])return;if(o[3]===o[0]&&o[4]===o[1]&&o[5]===o[2])return;o=o.slice();const t=d.getAABB3Center(o);this._look2=c||t;const i=d.subVec3(this._eye1,this._look1,q),s=d.normalizeVec3(i),r=c?d.getAABB3DiagPoint(o,c):d.getAABB3Diag(o),n=e.fitFOV||this._fitFOV,a=Math.abs(r/Math.tan(n*d.DEGTORAD));this._orthoScale2=1.1*r,this._eye2[0]=this._look2[0]+s[0]*a,this._eye2[1]=this._look2[1]+s[1]*a,this._eye2[2]=this._look2[2]+s[2]*a,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(n||a||l)&&(this._flyingEyeLookUp=!!n&&!!a&&!!l,this._flyingEye=!!n&&!a,this._flyingLook=!!a&&!n,n&&(this._eye2[0]=n[0],this._eye2[1]=n[1],this._eye2[2]=n[2]),a&&(this._look2[0]=a[0],this._look2[1]=a[1],this._look2[2]=a[2]),l&&(this._up2[0]=l[0],this._up2[1]=l[1],this._up2[2]=l[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,o,n;if(e.aabb)i=e.aabb;else if(6===e.length)i=e;else if(e.eye||e.look||e.up)r=e.eye,o=e.look,n=e.up;else{let t=e;if((y.isNumeric(t)||y.isString(t))&&(s=t,t=this.scene.components[s],!t))return void this.error("Component not found: "+y.inQuotes(s));i=t.aabb||this.scene.aabb}const a=e.poi;if(i){if(i[3]<=i[0]||i[4]<=i[1]||i[5]<=i[2])return;var l=a?d.getAABB3DiagPoint(i,a):d.getAABB3Diag(i);let s;o=a||d.getAABB3Center(i,o),this._trail?d.subVec3(t.look,o,ie):d.subVec3(t.eye,t.look,ie),d.normalizeVec3(ie);s=(void 0!==e.fit?e.fit:this._fit)?Math.abs(l/Math.tan((e.fitFOV||this._fitFOV)*d.DEGTORAD)):d.lenVec3(d.subVec3(t.eye,t.look,q)),d.mulVec3Scalar(ie,s),t.eye=d.addVec3(o,ie,q),t.look=o,this.scene.camera.ortho.scale=1.1*l}else(r||o||n)&&(r&&(t.eye=r),o&&(t.look=o),n&&(t.up=n));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,$)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,$),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,$),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 R{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 oe extends R{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),g.memory.meshes++}destroy(){super.destroy(),g.memory.meshes--}}const ne=new e({});class ae{constructor(e){this.id=ne.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ne.removeItem(this.id)}}class le{constructor(e,t,i,s,r,o,n,a,l){switch(this._gl=e,this.type=t,this.allocated=!1,this.ConstructorType=i.constructor,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=o,this.length=0,this.dataLength=s,this.numItems=0,this.itemSize=r,this.normalized=!!n,this.stride=a||0,this.offset=l||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)))}getData(e=0,t=this.numItems-e){if(!this.allocated)return[];const i=new this.ConstructorType(t*this.itemSize);return this._gl.bindBuffer(this.type,this._handle),this._gl.getBufferSubData(this.type,e*this.itemByteSize*this.itemSize,i,0,t*this.itemSize),i}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}var Ae=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),m=d.vec3();return function(g,_,v,b){!function(r,o){const n={};let a,l,A,c;const h=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;u<d;u+=3)a=r[u],l=r[u+1],A=r[u+2],c=Math.round(a*h)+"_"+Math.round(l*h)+"_"+Math.round(A*h),void 0===n[c]&&(n[c]=p/3,e[p++]=a,e[p++]=l,e[p++]=A),t[u/3]=n[c];for(u=0,d=o.length;u<d;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,_),function(t,i){o=0;for(let g=0,_=t;g<_;g+=3){const t=3*s[g],_=3*s[g+1],v=3*s[g+2];i?(n[0]=e[t],n[1]=e[t+1],n[2]=e[t+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],d.decompressPosition(n,i,A),d.decompressPosition(a,i,c),d.decompressPosition(l,i,h)):(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],h[0]=e[v],h[1]=e[v+1],h[2]=e[v+2]),d.subVec3(h,c,u),d.subVec3(A,c,p),d.cross3Vec3(u,p,f),d.normalizeVec3(f,m);const b=r[o]||(r[o]={normal:d.vec3()});b.normal[0]=m[0],b.normal[1]=m[1],b.normal[2]=m[2],o++}}(_.length,v);const y=[],w=Math.cos(d.DEGTORAD*b),B={};let P,x,C,M,E,F,I,T,D,S,R,U=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)P=s[e+i],x=s[e+(i+1)%3],C=Math.min(P,x),M=Math.max(P,x),E=C+","+M,void 0===B[E]?B[E]={index1:C,index2:M,face1:t,face2:void 0}:B[E].face2=t}for(E in B)F=B[E],void 0!==F.face2&&(I=r[F.face1].normal,T=r[F.face2].normal,D=d.dotVec3(I,T),D>w)||(S=i[F.index1],R=i[F.index2],(!U&&S>65535||R>65535)&&(U=!0),y.push(S),y.push(R));return U?new Uint32Array(y):new Uint16Array(y)}}();const ce=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,c=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([a/c,l/c,A/c],t),d.mulMat4(e,t,s),s}}();var he=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=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 a;for(a=0;a<i.length;a+=3)o[a+0]=Math.max(0,Math.min(65535,Math.floor((i[a+0]-s[0])*n[0]))),o[a+1]=Math.max(0,Math.min(65535,Math.floor((i[a+1]-s[1])*n[1]))),o[a+2]=Math.max(0,Math.min(65535,Math.floor((i[a+2]-s[2])*n[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:o,decodeMatrix:d.mulMat4(e,t,d.identityMat4())}}}();var ue=function(){const e=d.mat3(),t=d.mat3();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);let a;for(a=0;a<i.length;a+=2)o[a+0]=Math.max(0,Math.min(65535,Math.floor((i[a+0]-s[0])*n[0]))),o[a+1]=Math.max(0,Math.min(65535,Math.floor((i[a+1]-s[1])*n[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:o,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])),o=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(o))*(r>=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function pe(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 fe(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const me={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,o,n;for(let a=0;a<e.length;a+=3)r=i=de(e,a,"floor","floor"),s=pe(i),o=n=fe(e,a,s),i=de(e,a,"ceil","floor"),s=pe(i),o=fe(e,a,s),o>n&&(r=i,n=o),i=de(e,a,"floor","ceil"),s=pe(i),o=fe(e,a,s),o>n&&(r=i,n=o),i=de(e,a,"ceil","ceil"),s=pe(i),o=fe(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+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],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const n=1-Math.abs(r)-Math.abs(o);n<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,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 o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},ge=g.memory,_e=d.AABB3();class ve extends oe{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new ae({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=me.getPositionsBounds(t.positions),s=me.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=me.getUVBounds(t.uv),s=me.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);t.normals&&(this._state.compressGeometry?i.normals=me.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(),ge.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new le(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),ge.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new le(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),ge.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new le(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),ge.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new le(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),ge.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new le(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),ge.uvs+=e.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=Ae(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new le(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),ge.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 le(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new le(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),ge.positions+=this._pickTrianglePositionsBuf.numItems,ge.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}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),me.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=me.getPositionsBounds(e),s=me.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),me.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),me.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 o=d.vec3([0,0,0]);for(let t=0;t<e.length;t+=3){const e=i(t,s[0]),n=i(t+1,s[1]),a=i(t+2,s[2]);d.addVec3(e,n,s[3]),d.addVec3(a,s[3],s[3]);const l=d.lenVec3(d.cross3Vec3(d.subVec3(n,e,s[1]),d.subVec3(a,e,s[2]),s[0]))/2;r+=l,d.mulVec3Scalar(s[3],l,s[3]),d.addVec3(o,s[3],o)}this._metrics={surfaceArea:r,centroid:d.mulVec3Scalar(o,1/r/3,o)};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(),ge.meshes--}}const be=g.memory,ye=d.AABB3();class we extends oe{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new ae({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=me.getPositionsBounds(t.positions),o=me.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new le(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),be.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,ye,i.positionsDecodeMatrix),d.AABB3ToOBB3(ye,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new le(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),be.colors+=i.colorsBuf.numItems}if(t.uv){const e=me.getUVBounds(t.uv),r=me.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new le(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),be.uvs+=i.uvBuf.numItems}if(t.normals){const e=me.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new le(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),be.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new le(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),be.indices+=i.indicesBuf.numItems;const o=Ae(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new le(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),be.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(),be.meshes--}}var Be={};function Pe(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=Be.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function xe(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=Be.parse.fromOBJ(e),n=Be.edit.unwrap(o.i_verts,o.c_verts,3),a=Be.edit.unwrap(o.i_norms,o.c_norms,3),l=Be.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),c=0;c<o.i_verts.length;c++)A[c]=c;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:a.length>0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function Ce(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,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,c=-s+a,h=t+o,u=i+n,d=s+a;return y.apply(e,{positions:[h,u,d,l,u,d,l,A,d,h,A,d,h,u,d,h,A,d,h,A,c,h,u,c,h,u,d,h,u,c,l,u,c,l,u,d,l,u,d,l,u,c,l,A,c,l,A,d,l,A,c,h,A,c,h,A,d,l,A,d,h,A,c,l,A,c,l,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 Me(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,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,c=-s+a,h=t+o,u=i+n,d=s+a;return y.apply(e,{primitive:"lines",positions:[l,A,c,l,A,d,l,u,c,l,u,d,h,A,c,h,A,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 Ee(e={}){return Me({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 Fe(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 o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,c=a?a[2]:0,h=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,m=[],g=[],_=[],v=[];let b,w,B,P,x,C,M,E,F,I,T;const D=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(b=0;b<=o;b++)for(x=t-b*f,C=h-b*u,w=0;w<=r;w++)B=Math.sin(w*d),P=Math.cos(w*d),g.push(x*B),g.push(D),g.push(x*P),_.push(w*p),_.push(1*b/o),m.push(x*B+l),m.push(C+A),m.push(x*P+c);for(b=0;b<o;b++)for(w=0;w<=r;w++)M=b*(r+1)+w,E=M+r,v.push(M),v.push(E),v.push(E+1),v.push(M),v.push(E+1),v.push(M+1);if(!n&&t>0){for(F=m.length/3,g.push(0),g.push(1),g.push(0),_.push(.5),_.push(.5),m.push(0+l),m.push(h+A),m.push(0+c),w=0;w<=r;w++)B=Math.sin(w*d),P=Math.cos(w*d),I=.5*Math.sin(w*d)+.5,T=.5*Math.cos(w*d)+.5,g.push(t*B),g.push(1),g.push(t*P),_.push(I),_.push(T),m.push(t*B+l),m.push(h+A),m.push(t*P+c);for(w=0;w<r;w++)a=F,M=F+1+w,v.push(M),v.push(M+1),v.push(a)}if(!n&&i>0){for(F=m.length/3,g.push(0),g.push(-1),g.push(0),_.push(.5),_.push(.5),m.push(0+l),m.push(0-h+A),m.push(0+c),w=0;w<=r;w++)B=Math.sin(w*d),P=Math.cos(w*d),I=.5*Math.sin(w*d)+.5,T=.5*Math.cos(w*d)+.5,g.push(i*B),g.push(-1),g.push(i*P),_.push(I),_.push(T),m.push(i*B+l),m.push(0-h+A),m.push(i*P+c);for(w=0;w<r;w++)a=F,M=F+1+w,v.push(a),v.push(M+1),v.push(M)}return y.apply(e,{positions:m,normals:g,uv:_,indices:v})}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,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return y.apply(e,{primitive:"lines",positions:o,indices:n})}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 o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,c=i/2,h=Math.floor(s)||1,u=Math.floor(r)||1,d=h+1,p=u+1,f=t/h,m=i/u,g=new Float32Array(d*p*3),_=new Float32Array(d*p*3),v=new Float32Array(d*p*2);let b,w,B,P,x,C,M,E=0,F=0;for(b=0;b<p;b++){const e=b*m-c;for(w=0;w<d;w++)B=w*f-A,g[E]=B+n,g[E+1]=a,g[E+2]=-e+l,_[E+1]=1,v[F]=w/h,v[F+1]=(u-b)/u,E+=3,F+=2}E=0;const I=new(g.length/3>65535?Uint32Array:Uint16Array)(h*u*6);for(b=0;b<u;b++)for(w=0;w<h;w++)P=w+d*b,x=w+d*(b+1),C=w+1+d*(b+1),M=w+1+d*b,I[E]=M,I[E+1]=x,I[E+2]=P,I[E+3]=M,I[E+4]=C,I[E+5]=x,E+=6;return y.apply(e,{positions:g,normals:_,uv:v,indices:I})}function De(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 o=e.radius||1;o<0&&(console.error("negative radius not allowed - will invert"),o*=-1);let n=e.heightSegments||18;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n=Math.floor(t*n),n<18&&(n=18);let a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),a=Math.floor(t*a),a<18&&(a=18);const l=[],A=[],c=[],h=[];let u,d,p,f,m,g,_,v,b,w,B,P,x,C,M;for(u=0;u<=n;u++)for(p=u*Math.PI/n,f=Math.sin(p),m=Math.cos(p),d=0;d<=a;d++)g=2*d*Math.PI/a,_=Math.sin(g),v=Math.cos(g),b=v*f,w=m,B=_*f,P=1-d/a,x=u/n,A.push(b),A.push(w),A.push(B),c.push(P),c.push(x),l.push(i+o*b),l.push(s+o*w),l.push(r+o*B);for(u=0;u<n;u++)for(d=0;d<a;d++)C=u*(a+1)+d,M=C+a+1,h.push(C+1),h.push(M+1),h.push(M),h.push(C+1),h.push(M),h.push(C);return y.apply(e,{positions:l,normals:A,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 o=e.arc||2*Math.PI;o<0&&(console.warn("negative arc not allowed - will invert"),o*=-1),o>360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,c=[],h=[],u=[],p=[];let f,m,g,_,v,b,w,B,P,x,C,M;for(B=0;B<=r;B++)for(w=0;w<=s;w++)f=w/s*o,m=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),g=(t+i*Math.cos(m))*Math.cos(f),_=(t+i*Math.cos(m))*Math.sin(f),v=i*Math.sin(m),c.push(g+a),c.push(_+l),c.push(v+A),u.push(1-w/s),u.push(B/r),b=d.normalizeVec3(d.subVec3([g,_,v],[a,l,A],[]),[]),h.push(b[0]),h.push(b[1]),h.push(b[2]);for(B=1;B<=r;B++)for(w=1;w<=s;w++)P=(s+1)*B+w-1,x=(s+1)*(B-1)+w-1,C=(s+1)*(B-1)+w,M=(s+1)*B+w,p.push(P),p.push(x),p.push(C),p.push(C),p.push(M),p.push(P);return y.apply(e,{positions:c,normals:h,uv:u,indices:p})}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 o=Be.parse._readLine(r,s);s+=o.length+1;var n=(o=(o=o.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==n[0]&&(i.to=t.i_verts.length,null==t.groups[n[1]]&&(t.groups[n[1]]={from:t.i_verts.length,to:0}),i=t.groups[n[1]]),"v"==n[0]){var a=parseFloat(n[1]),l=parseFloat(n[2]),A=parseFloat(n[3]);t.c_verts.push(a,l,A)}if("vt"==n[0]){a=parseFloat(n[1]),l=1-parseFloat(n[2]);t.c_uvt.push(a,l)}if("vn"==n[0]){a=parseFloat(n[1]),l=parseFloat(n[2]),A=parseFloat(n[3]);t.c_norms.push(a,l,A)}if("f"==n[0]){var c=n[1].split("/"),h=n[2].split("/"),u=n[3].split("/"),d=parseInt(c[0])-1,p=parseInt(h[0])-1,f=parseInt(u[0])-1,m=parseInt(c[1])-1,g=parseInt(h[1])-1,_=parseInt(u[1])-1,v=parseInt(c[2])-1,b=parseInt(h[2])-1,y=parseInt(u[2])-1,w=t.c_verts.length/3,B=t.c_uvt.length/2,P=t.c_norms.length/3;if(d<0&&(d=w+d+1),p<0&&(p=w+p+1),f<0&&(f=w+f+1),m<0&&(m=B+m+1),g<0&&(g=B+g+1),_<0&&(_=B+_+1),v<0&&(v=P+v+1),b<0&&(b=P+b+1),y<0&&(y=P+y+1),t.i_verts.push(d,p,f),t.i_uvt.push(m,g,_),t.i_norms.push(v,b,y),5==n.length){var x=n[4].split("/"),C=parseInt(x[0])-1,M=parseInt(x[1])-1,E=parseInt(x[2])-1;C<0&&(C=w+C+1),M<0&&(M=B+M+1),E<0&&(E=P+E+1),t.i_verts.push(d,f,C),t.i_uvt.push(m,_,M),t.i_norms.push(v,y,E)}}}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 o=Be.bin.rsl(e,s)/i.skinwidth,n=Be.bin.rsl(e,s+2)/i.skinheight;t.c_uvt.push(o,n),s+=4}s=i.offset_tris;var a=[],l=[];t.i_verts=a,t.i_uvt=l;for(r=0;r<i.num_tris;r++)a.push(Be.bin.rsl(e,s),Be.bin.rsl(e,s+2),Be.bin.rsl(e,s+4)),l.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 A=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 p=Be.bin.rf(e,s),f=Be.bin.rf(e,s+4),m=Be.bin.rf(e,s+8);s+=12,c.name=Be.bin.rASCII0(e,s),s+=16,c.verts=[],c.norms=[];for(var g=0;g<i.num_vertices;g++)c.verts.push(e[s]*h+p,e[s+1]*u+f,e[s+2]*d+m),c.norms.push(A[3*e[s+3]],A[3*e[s+3]+1],A[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],o=i.getElementsByTagName("library_geometries")[0],n=i.getElementsByTagName("library_images")[0],a=i.getElementsByTagName("library_materials")[0],l=i.getElementsByTagName("library_effects")[0];return r&&(s.asset=Be.parse.fromCollada._asset(r)),o&&(s.geometries=Be.parse.fromCollada._libGeometries(o)),n&&(s.images=Be.parse.fromCollada._libImages(n)),a&&(s.materials=Be.parse.fromCollada._libMaterials(a)),l&&(s.effects=Be.parse.fromCollada._libEffects(l)),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 o=i[r].getElementsByTagName("float_array")[0].textContent.split(" "),n=o.length-(""==o[o.length-1]?1:0),a=new Array(n),l=0;l<n;l++)a[l]=parseFloat(o[l]);s[i[r].getAttribute("id")]=a}t.triangles=[];var A=e.getElementsByTagName("triangles");if(null==A)return t;for(r=0;r<A.length;r++){var c={},h=A[r];c.material=h.getAttribute("material");var u=h.getElementsByTagName("input"),d=[];for(l=0;l<u.length;l++){var p=u[l];a=[];d[parseInt(p.getAttribute("offset"))]=a;var f=p.getAttribute("semantic");c["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):p.getAttribute("source").substring(1),c["i_"+f]=a,s[c["s_"+f]]}var m=h.getElementsByTagName("p")[0].textContent.split(" "),g=3*Math.floor(m.length/3);for(l=0;l<g;l++)d[l%u.length].push(parseInt(m[l]));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"),o=0;o<r.length;o++){var n=r[o].getElementsByTagName("surface")[0];n&&(s.surface=n.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),o=Be.bin.ril(e,s+2);15677==r&&(t.edit=Be.parse.from3DS._edit3ds(e,s,o)),45056==r&&(t.keyf=Be.parse.from3DS._keyf3ds(e,s,o)),s+=o}return t},Be.parse.from3DS._edit3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Be.bin.rsl(e,r),n=Be.bin.ril(e,r+2);16384==o&&(null==s.objects&&(s.objects=[]),s.objects.push(Be.parse.from3DS._edit_object(e,r,n))),r+=n}return s},Be.parse.from3DS._keyf3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Be.bin.rsl(e,r),n=Be.bin.ril(e,r+2);45058==o&&(null==s.desc&&(s.desc=[]),s.desc.push(Be.parse.from3DS._keyf_objdes(e,r,n))),r+=n}return s},Be.parse.from3DS._keyf_objdes=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Be.bin.rsl(e,r),n=Be.bin.ril(e,r+2);45072==o&&(s.hierarchy=Be.parse.from3DS._keyf_objhierarch(e,r,n)),45073==o&&(s.dummy_name=Be.bin.rASCII0(e,r+6)),r+=n}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 o=Be.bin.rsl(e,r),n=Be.bin.ril(e,r+2);16640==o&&(s.mesh=Be.parse.from3DS._obj_trimesh(e,r,n)),r+=n}return s},Be.parse.from3DS._obj_trimesh=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Be.bin.rsl(e,r),n=Be.bin.ril(e,r+2);16656==o&&(s.vertices=Be.parse.from3DS._tri_vertexl(e,r,n)),16672==o&&(s.indices=Be.parse.from3DS._tri_facel1(e,r,n)),16704==o&&(s.uvt=Be.parse.from3DS._tri_mappingcoors(e,r,n)),16736==o&&(s.local=Be.parse.from3DS._tri_local(e,r,n)),r+=n}return s},Be.parse.from3DS._tri_vertexl=function(e,t,i){var s=[],r=t+6,o=Be.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)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,o=Be.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)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,o=Be.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)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 o=new Uint8Array(r);Be.bin.wil(o,0,1769365870),Be.bin.wil(o,4,32),Be.bin.wil(o,8,32),Be.bin.wil(o,12,s);var n=40;return e.vertices&&(Be.bin.wil(o,16,n),Be.bin.wil(o,20,4*e.vertices.length),Be.parse.fromBIV._writeFloats(o,n,e.vertices),n+=4*e.vertices.length),e.uvt&&(Be.bin.wil(o,24,n),Be.bin.wil(o,28,4*e.uvt.length),Be.parse.fromBIV._writeFloats(o,n,e.uvt),n+=4*e.uvt.length),e.indices&&(Be.bin.wil(o,32,n),Be.bin.wil(o,36,4*e.indices.length),Be.parse.fromBIV._writeInts(o,n,e.indices,s)),o.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=[],o=0;o<i/4;o++)16==s&&r.push(Be.bin.rsl(e,t+2*o)),32==s&&r.push(Be.bin.ril(e,t+4*o));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:[]},o=e+1,n=t+1,a=0;a<n;a++)for(var l=0;l<o;l++){var A=l*(2/e)-1,c=a*(2/t)-1;r.verts.push(A,c,0),r.uvt.push(i*l/e,s*a/t),a<t&&l<e&&r.inds.push(a*o+l,a*o+l+1,(a+1)*o+l,a*o+l+1,(a+1)*o+l,(a+1)*o+l+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,o=0;o<r;o++)for(var n=0;n<s;n++){var a=-Math.PI/2+o*Math.PI/t,l=2*n*Math.PI/e,A=Math.cos(a)*Math.cos(l),c=Math.sin(a),h=Math.cos(a)*Math.sin(l);i.verts.push(A,c,h),i.uvt.push(n/e,o/t),o<t&&n<e&&i.inds.push(s*o+n,s*o+n+1,s*(o+1)+n,s*o+n+1,s*(o+1)+n,s*(o+1)+n+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,o=t,n=i,a=Math.cos(r),l=Math.cos(o),A=Math.cos(n),c=Math.sin(r),h=Math.sin(o),u=Math.sin(n);return s[0]=l*A,s[1]=-l*u,s[2]=h,s[4]=a*u+c*h*A,s[5]=a*A-c*h*u,s[6]=-c*l,s[8]=c*u-a*h*A,s[9]=c*A+a*h*u,s[10]=a*l,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],o=e[i+2];e[i+0]=t[0]*s+t[4]*r+t[8]*o+t[12],e[i+1]=t[1]*s+t[5]*r+t[9]*o+t[13],e[i+2]=t[2]*s+t[6]*r+t[10]*o+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 o=0;o<i;o++)s[r*i+o]=t[e[r]*i+o];return s},Be.edit.remap=function(e,t,i,s){for(var r=new Array(i.length),o=0;o<e.length;o++)for(var n=0;n<s;n++)r[t[o]*s+n]=i[e[o]*s+n];return r},Be.utils={},Be.utils.getAABB=function(e){var t,i,s,r,o,n;r=o=n=-(t=i=s=999999999);for(var a=0;a<e.length;a+=3){var l=e[a+0],A=e[a+1],c=e[a+2];l<t&&(t=l),l>r&&(r=l),A<i&&(i=A),A>o&&(o=A),c<s&&(s=c),A>n&&(n=c)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};const Re={" ":{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 Ue(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;y.isNumeric(l)&&(l=""+l);for(var A,c,h,u,d,p,f,m,g,_=(l||"").split("\n"),v=0,b=0,w=.04,B=0;B<_.length;B++){A=0,h=(c=_[B]).length;for(var P=0;P<h;P++)if(u=Re[c.charAt(P)]){d=1,p=-1,f=-1,m=u.points.length;for(var x=0;x<m;x++)-1!==(g=u.points[x])[0]||-1!==g[1]?(n.push(A+g[0]*o*w+i),n.push(b+g[1]*o*w+s),n.push(0+r),-1===p?p=v:(-1===f||(p=f),f=v),v++,d?d=!1:(a.push(p),a.push(f))):d=1;A+=u.width*w*o}b-=35*w*o}return y.apply(e,{primitive:"lines",positions:n,indices:a})}function Le(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 y.apply(e,{primitive:"lines",positions:e.points,indices:i})}function ke(e={}){let t=e.curve.getPoints(e.divisions).map((e=>[...e])).flat();return Le({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],o=e.startPoint[2],n=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],A=Math.sqrt((n-s)**2+(a-r)**2+(l-o)**2),c=[(n-s)/A,(a-r)/A,(l-o)/A];if(e.pattern){let h=e.pattern.length,u=!1,d=0,p=0,f=0,m=[s,r,o],g=e.pattern[p];for(i.push(m[0],m[1],m[2]);g<=A-d;){let s=[c[0]*g,c[1]*g,c[2]*g],r=[m[0]+s[0],m[1]+s[1],m[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(f),t.push(f+1)),u=!u,f+=1,m=r,p+=1,p>=h&&(p=0),d+=g,g=e.pattern[p]}e.extendToEnd&&(i.push(n,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,o,n,a,l);return y.apply(e,{primitive:"lines",positions:i,indices:t})}const Ne=d.vec4(4),Ve=d.vec4(),Qe=d.vec4(),He=d.vec3([1,0,0]),je=d.vec3([0,1,0]),Ge=d.vec3([0,0,1]),ze=d.vec3(3),We=d.vec3(3),Xe=d.identityMat4();class Ke extends R{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(y.isNumeric(e)||y.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+y.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(y.isNumeric(e)||y.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+y.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 Ne[0]=e[0],Ne[1]=e[1],Ne[2]=e[2],Ne[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Ne,Ve),d.mulQuaternions(this.quaternion,Ve,Qe),this.quaternion=Qe,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ne[0]=e[0],Ne[1]=e[1],Ne[2]=e[2],Ne[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Ne,Ve),d.mulQuaternions(Ve,this.quaternion,Ve),this}rotateX(e){return this.rotate(He,e)}rotateY(e){return this.rotate(je,e)}rotateZ(e){return this.rotate(Ge,e)}translate(e,t){return d.vec3ApplyQuaternion(this.quaternion,e,ze),d.mulVec3Scalar(ze,t,We),d.addVec3(this.position,We,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(He,e)}translateY(e){return this.translate(je,e)}translateZ(e){return this.translate(Ge,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=d.vec4(),Ye=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||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,o),o.slice()}}();function qe(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function $e(e,t,i,s=1e3){const r=d.getPositionsCenter(e,Ze),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i<s;i+=3)t[i+0]=e[i+0]-o,t[i+1]=e[i+1]-n,t[i+2]=e[i+2]-a;return l}function et(e,t,i){return i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i}function tt(e,t,i,s,r){const o=r?(Je.set(i,0),Je[3]=1,d.mulMat4v4(r,Je,Je)):i,n=d.dotVec3(t,o)+e,a=d.normalizeVec3(t,Ze);return d.mulVec3Scalar(a,-n,s),s}const it=1e3,st=1001,rt=1002,ot=1003,nt=1004,at=1004,lt=1005,At=1005,ct=1006,ht=1007,ut=1007,dt=1008,pt=1008,ft=1009,mt=1010,gt=1011,_t=1012,vt=1013,bt=1014,yt=1015,wt=1016,Bt=1017,Pt=1018,xt=1020,Ct=1021,Mt=1022,Et=1023,Ft=1024,It=1025,Tt=1026,Dt=1027,St=1028,Rt=1029,Ut=1030,Lt=1031,kt=1033,Ot=33776,Nt=33777,Vt=33778,Qt=33779,Ht=35840,jt=35841,Gt=35842,zt=35843,Wt=36196,Xt=37492,Kt=37496,Zt=37808,Jt=37809,Yt=37810,qt=37811,$t=37812,ei=37813,ti=37814,ii=37815,si=37816,ri=37817,oi=37818,ni=37819,ai=37820,li=37821,Ai=36492,ci=3e3,hi=3001,ui=1e4,di=10001,pi=10002,fi=10003,mi=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),A.push("uniform vec3 scale;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(A.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&A.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&A.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(A.push("uniform vec3 lightPos"+e+";"),A.push("uniform vec3 lightDir"+e+";")))}l&&(A.push("vec3 octDecode(vec2 oct) {"),A.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),A.push(" if (v.z < 0.0) {"),A.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);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = scale[0];"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = scale[1];"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?A.push("viewLightDir = normalize(lightDir"+e+");"):A.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?A.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):A.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?A.push("viewLightDir = normalize(lightDir"+e+");"):A.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}A.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),A.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}A.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),a&&A.push("vWorldPosition = worldPosition;");"points"===r.primitiveName&&A.push("gl_PointSize = pointSize;");A.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(A.push("vFragDepth = 1.0 + clipPos.w;"),A.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return A.push("gl_Position = clipPos;"),A.push("}"),A}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState;e._material._state;const s=e._geometry._state,r=i.getNumAllocatedSectionPlanes()>0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}n.push("in vec4 vColor;"),o&&(n.push("uniform float gammaFactor;"),n.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push("if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=vi(e),u=s.getNumAllocatedSectionPlanes()>0,d=_i(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),f.push("uniform vec3 scale;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e<t;e++)n=o.lights[e],"ambient"!==n.type&&("dir"===n.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===n.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===n.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===n.type&&"view"===n.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));p&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.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);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = scale[0];"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = scale[1];"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = 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);");for(let e=0,t=o.lights.length;e<t;e++)o.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(p?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),A?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),o.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e<t;e++)n=o.lights[e],"ambient"!==n.type&&("dir"===n.type&&"world"===n.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===n.type&&("world"===n.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}c&&(p?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));r.colors&&f.push("vColor = color;");"points"===r.primitiveName&&f.push("gl_PointSize = pointSize;");u&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));l&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),d){f.push("const mat4 texUnitConverter = 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);"),f.push("vec4 tempx; ");for(let e=0,t=o.lights.length;e<t;e++)o.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=e._material,s=e._geometry._state,r=e.scene._sectionPlanesState,o=e.scene._lightsState,n=e._material._state,a=r.getNumAllocatedSectionPlanes()>0,l=vi(e),A=s.uvBuf,c="PhongMaterial"===n.type,h="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=_i(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.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));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var m=0;m<r.getNumAllocatedSectionPlanes();m++)f.push("uniform bool sectionPlaneActive"+m+";"),f.push("uniform vec3 sectionPlanePos"+m+";"),f.push("uniform vec3 sectionPlaneDir"+m+";")}l&&(o.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+gi[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+gi[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e<t;e++){const t=o.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(d)for(let e=0,t=o.lights.length;e<t;e++)o.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),a){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(m=0;m<r.getNumAllocatedSectionPlanes();m++)f.push("if (sectionPlaneActive"+m+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+m+".xyz, vWorldPosition.xyz - sectionPlanePos"+m+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+gi[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+gi[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+gi[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+gi[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||h)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e<t;e++){const t=o.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),d&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),c&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(u||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}c?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),p&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},gi={};function _i(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,i=t.length;e<i;e++)if(t[e].castsShadow)return!0;return!1}function vi(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}gi[3e3]="linearToLinear",gi[3001]="sRGBToLinear";class bi{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e<t.length;e++)s.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(s.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class yi{constructor(e,t){this.bindTexture=function(i,s){return!!i.bind(s)&&(e.uniform1i(t,s),!0)}}}class wi{constructor(e,t){this._gl=e,this.location=t}bindArrayBuffer(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}const Bi=new e({});function Pi(e){const t=[];let i,s;for(let r=0,o=e.length;r<o;r++)i=e[r],s=i.indexOf("/"),s>0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function xi(e){console.error(e.join("\n"))}class Ci{constructor(e,t){this.id=Bi.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new bi(e,e.VERTEX_SHADER,Pi(this.source.vertex)),this._fragmentShader=new bi(e,e.FRAGMENT_SHADER,Pi(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void xi(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void xi(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void xi(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void xi(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void xi(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<n;++i)s=e.getActiveUniform(this.handle,i),s&&(r=s.name,"\0"===r[r.length-1]&&(r=r.substr(0,r.length-1)),o=e.getUniformLocation(this.handle,r),s.type===e.SAMPLER_2D||s.type===e.SAMPLER_CUBE||35682===s.type||e instanceof WebGL2RenderingContext&&(s.type===e.UNSIGNED_INT_SAMPLER_2D||s.type===e.INT_SAMPLER_2D)?this.samplers[r]=new yi(e,o):this.uniforms[r]=o);const a=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<a;i++)t=e.getActiveAttrib(this.handle,i),t&&(o=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new wi(e,o));this.allocated=!0}bind(){this.allocated&&this.gl.useProgram(this.handle)}getLocation(e){if(this.allocated)return this.uniforms[e]}getAttribute(e){if(this.allocated)return this.attributes[e]}bindTexture(e,t,i){if(!this.allocated)return!1;const s=this.samplers[e];return!!s&&s.bindTexture(t,i)}destroy(){this.allocated&&(Bi.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}const Mi={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},Ei=document.createElement("canvas");if(Ei){const e=Ei.getContext("webgl",{antialias:!0})||Ei.getContext("experimental-webgl",{antialias:!0});Mi.WEBGL=!!e,Mi.WEBGL&&(Mi.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?Mi.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Mi.FS_MAX_FLOAT_PRECISION="mediump":Mi.FS_MAX_FLOAT_PRECISION="lowp":Mi.FS_MAX_FLOAT_PRECISION="mediump",Mi.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Mi.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Mi.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Mi.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Mi.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Mi.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Mi.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Mi.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Mi.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Mi.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Mi.SUPPORTED_EXTENSIONS[e]=!0})))}const Fi=d.vec3(),Ii=new e({}),Ti=function(e,t){this.id=Ii.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new mi(t),this._allocate(t)},Di={};Ti.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let s=Di[i];if(!s){if(s=new Ti(i,e),s.errors)return console.log(s.errors.join("\n")),null;Di[i]=s,g.memory.programs++}return s._useCount++,s},Ti.prototype.put=function(){0==--this._useCount&&(Ii.removeItem(this.id),this._program&&this._program.destroy(),delete Di[this._hash],g.memory.programs--)},Ti.prototype.webglContextRestored=function(){this._program=null},Ti.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=Mi.MAX_TEXTURE_UNITS,s=t.scene,r=t._material,o=s.canvas.gl,n=this._program,a=t._state,l=t._material._state,A=t._geometry._state,c=s.camera,h=t.origin,u=a.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,u&&o.depthFunc(o.LEQUAL),this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):c.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,c.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(h){const t=tt(i.dist,i.dir,h,Fi);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}if(l.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=l.backfaces;e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t);const s=l.frontface;switch(e.frontface!==s&&(s?o.frontFace(o.CCW):o.frontFace(o.CW),e.frontface=s),e.lineWidth!==l.lineWidth&&(o.lineWidth(l.lineWidth),e.lineWidth=l.lineWidth),this._uPointSize&&o.uniform1f(this._uPointSize,l.pointSize),l.type){case"LambertMaterial":this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialColor&&o.uniform4f(this._uMaterialColor,l.color[0],l.color[1],l.color[2],l.alpha),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive);break;case"PhongMaterial":this._uMaterialShininess&&o.uniform1f(this._uMaterialShininess,l.shininess),this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0),r._ambientMap&&r._ambientMap._state.texture&&this._uMaterialAmbientMap&&(n.bindTexture(this._uMaterialAmbientMap,r._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMaterialAmbientMapMatrix&&o.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,r._ambientMap._state.matrix)),r._diffuseMap&&r._diffuseMap._state.texture&&this._uDiffuseMap&&(n.bindTexture(this._uDiffuseMap,r._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,r._diffuseMap._state.matrix)),r._specularMap&&r._specularMap._state.texture&&this._uSpecularMap&&(n.bindTexture(this._uSpecularMap,r._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,r._specularMap._state.matrix)),r._emissiveMap&&r._emissiveMap._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,r._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,r._emissiveMap._state.matrix)),r._alphaMap&&r._alphaMap._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,r._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,r._alphaMap._state.matrix)),r._reflectivityMap&&r._reflectivityMap._state.texture&&this._uReflectivityMap&&(n.bindTexture(this._uReflectivityMap,r._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,this._uReflectivityMapMatrix&&o.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,r._reflectivityMap._state.matrix)),r._normalMap&&r._normalMap._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,r._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,r._normalMap._state.matrix)),r._occlusionMap&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,r._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,r._occlusionMap._state.matrix)),r._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&o.uniform1f(this._uDiffuseFresnelEdgeBias,r._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&o.uniform1f(this._uDiffuseFresnelCenterBias,r._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&o.uniform3fv(this._uDiffuseFresnelEdgeColor,r._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&o.uniform3fv(this._uDiffuseFresnelCenterColor,r._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&o.uniform1f(this._uDiffuseFresnelPower,r._diffuseFresnel.power)),r._specularFresnel&&(this._uSpecularFresnelEdgeBias&&o.uniform1f(this._uSpecularFresnelEdgeBias,r._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&o.uniform1f(this._uSpecularFresnelCenterBias,r._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&o.uniform3fv(this._uSpecularFresnelEdgeColor,r._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&o.uniform3fv(this._uSpecularFresnelCenterColor,r._specularFresnel.centerColor),this._uSpecularFresnelPower&&o.uniform1f(this._uSpecularFresnelPower,r._specularFresnel.power)),r._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&o.uniform1f(this._uAlphaFresnelEdgeBias,r._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&o.uniform1f(this._uAlphaFresnelCenterBias,r._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&o.uniform3fv(this._uAlphaFresnelEdgeColor,r._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&o.uniform3fv(this._uAlphaFresnelCenterColor,r._alphaFresnel.centerColor),this._uAlphaFresnelPower&&o.uniform1f(this._uAlphaFresnelPower,r._alphaFresnel.power)),r._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&o.uniform1f(this._uReflectivityFresnelEdgeBias,r._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&o.uniform1f(this._uReflectivityFresnelCenterBias,r._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&o.uniform3fv(this._uReflectivityFresnelEdgeColor,r._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&o.uniform3fv(this._uReflectivityFresnelCenterColor,r._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&o.uniform1f(this._uReflectivityFresnelPower,r._reflectivityFresnel.power)),r._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&o.uniform1f(this._uEmissiveFresnelEdgeBias,r._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&o.uniform1f(this._uEmissiveFresnelCenterBias,r._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&o.uniform3fv(this._uEmissiveFresnelEdgeColor,r._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&o.uniform3fv(this._uEmissiveFresnelCenterColor,r._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&o.uniform1f(this._uEmissiveFresnelPower,r._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&o.uniform3fv(this._uBaseColor,l.baseColor),this._uMaterialMetallic&&o.uniform1f(this._uMaterialMetallic,l.metallic),this._uMaterialRoughness&&o.uniform1f(this._uMaterialRoughness,l.roughness),this._uMaterialSpecularF0&&o.uniform1f(this._uMaterialSpecularF0,l.specularF0),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const t=r._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(n.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uBaseColorMapMatrix&&o.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const s=r._metallicMap;s&&s._state.texture&&this._uMetallicMap&&(n.bindTexture(this._uMetallicMap,s._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicMapMatrix&&o.uniformMatrix4fv(this._uMetallicMapMatrix,!1,s._state.matrix));const a=r._roughnessMap;a&&a._state.texture&&this._uRoughnessMap&&(n.bindTexture(this._uRoughnessMap,a._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uRoughnessMapMatrix&&o.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,a._state.matrix));const A=r._metallicRoughnessMap;A&&A._state.texture&&this._uMetallicRoughnessMap&&(n.bindTexture(this._uMetallicRoughnessMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&o.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,A._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(f=r._alphaMap)&&f._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(m=r._normalMap)&&m._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,m._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialGlossiness&&o.uniform1f(this._uMaterialGlossiness,l.glossiness),this._uMaterialReflectivity&&o.uniform1f(this._uMaterialReflectivity,l.reflectivity),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const c=r._diffuseMap;c&&c._state.texture&&this._uDiffuseMap&&(n.bindTexture(this._uDiffuseMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,c._state.matrix));const h=r._specularMap;h&&h._state.texture&&this._uSpecularMap&&(n.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const u=r._glossinessMap;u&&u._state.texture&&this._uGlossinessMap&&(n.bindTexture(this._uGlossinessMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uGlossinessMapMatrix&&o.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,u._state.matrix));const g=r._specularGlossinessMap;var d,p,f,m;g&&g._state.texture&&this._uSpecularGlossinessMap&&(n.bindTexture(this._uSpecularGlossinessMap,g._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&o.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,g._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&p._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(f=r._alphaMap)&&f._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(m=r._normalMap)&&m._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,m._state.matrix))}this._lastMaterialId=l.id}if(o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),this._uColorize){const e=a.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(o.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}o.uniform3fv(this._uOffset,a.offset),o.uniform3fv(this._uScale,t.scale),A.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,A.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,A.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(A.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(A.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(A.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(A.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(A.flagsBuf),e.bindArray++),A.indicesBuf&&(A.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=A.id),A.indicesBuf?(o.drawElements(A.primitive,A.indicesBuf.numItems,A.indicesBuf.itemType,0),e.drawElements++):A.positions&&(o.drawArrays(o.TRIANGLES,0,A.positions.numItems),e.drawArrays++),u&&o.depthFunc(o.LESS)},Ti.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=e._material,r=t._lightsState,o=t._sectionPlanesState,n=e._material._state;if(this._program=new Ci(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=a.getLocation("uvDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC"));const l=r.lights;let A;for(var c=0,h=l.length;c<h;c++){switch(A=l[c],A.type){case"ambient":this._uLightAmbient[c]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=null,this._uLightDir[c]=a.getLocation("lightDir"+c);break;case"point":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=null,this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c);break;case"spot":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=a.getLocation("lightDir"+c),this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c)}A.castsShadow&&(this._uShadowViewMatrix[c]=a.getLocation("shadowViewMatrix"+c),this._uShadowProjMatrix[c]=a.getLocation("shadowProjMatrix"+c))}r.lightMaps.length>0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,h=o.sectionPlanes.length;c<h;c++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+c),pos:a.getLocation("sectionPlanePos"+c),dir:a.getLocation("sectionPlaneDir"+c)});switch(this._uPointSize=a.getLocation("pointSize"),n.type){case"LambertMaterial":this._uMaterialColor=a.getLocation("materialColor"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=a.getLocation("materialAmbient"),this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=a.getLocation("materialShininess"),s._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=a.getLocation("ambientMapMatrix")),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=a.getLocation("reflectivityMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=a.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=a.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=a.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=a.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=a.getLocation("diffuseFresnelPower")),s._specularFresnel&&(this._uSpecularFresnelEdgeBias=a.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=a.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=a.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=a.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=a.getLocation("specularFresnelPower")),s._alphaFresnel&&(this._uAlphaFresnelEdgeBias=a.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=a.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=a.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=a.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=a.getLocation("alphaFresnelPower")),s._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=a.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=a.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=a.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=a.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=a.getLocation("reflectivityFresnelPower")),s._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=a.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=a.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=a.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=a.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=a.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=a.getLocation("materialBaseColor"),this._uMaterialMetallic=a.getLocation("materialMetallic"),this._uMaterialRoughness=a.getLocation("materialRoughness"),this._uMaterialSpecularF0=a.getLocation("materialSpecularF0"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),s._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=a.getLocation("baseColorMapMatrix")),s._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=a.getLocation("metallicMapMatrix")),s._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=a.getLocation("roughnessMapMatrix")),s._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=a.getLocation("metallicRoughnessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialGlossiness=a.getLocation("materialGlossiness"),this._uMaterialReflectivity=a.getLocation("reflectivityFresnel"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),s._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=a.getLocation("glossinessMapMatrix")),s._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=a.getLocation("materialSpecularGlossinessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"))}this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._aUV=a.getAttribute("uv"),this._aColor=a.getAttribute("color"),this._aFlags=a.getAttribute("flags"),this._uClippable=a.getLocation("clippable"),this._uColorize=a.getLocation("colorize"),this._uOffset=a.getLocation("offset"),this._uScale=a.getLocation("scale"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},Ti.prototype._bindProgram=function(e){const t=Mi.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=i._lightsState,o=i.camera.project;let n;const a=this._program;if(a.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,s.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(var l=0,A=r.lights.length;l<A;l++)if(n=r.lights[l],this._uLightAmbient[l])s.uniform4f(this._uLightAmbient[l],n.color[0],n.color[1],n.color[2],n.intensity);else if(this._uLightColor[l]&&s.uniform4f(this._uLightColor[l],n.color[0],n.color[1],n.color[2],n.intensity),this._uLightPos[l]&&(s.uniform3fv(this._uLightPos[l],n.pos),this._uLightAttenuation[l]&&s.uniform1f(this._uLightAttenuation[l],n.attenuation)),this._uLightDir[l]&&s.uniform3fv(this._uLightDir[l],n.dir),n.castsShadow){this._uShadowViewMatrix[l]&&s.uniformMatrix4fv(this._uShadowViewMatrix[l],!1,n.getShadowViewMatrix()),this._uShadowProjMatrix[l]&&s.uniformMatrix4fv(this._uShadowProjMatrix[l],!1,n.getShadowProjMatrix());const i=n.getShadowRenderBuf();i&&(a.bindTexture("shadowMap"+l,i.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Si{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),l.push("uniform vec3 scale;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(l.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&l.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&l.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&l.push("uniform vec3 lightPos"+e+";"))}o&&(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.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);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = scale[0];"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = scale[1];"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?l.push("viewLightDir = normalize(lightDir"+e+");"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?l.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}l.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),r&&l.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&l.push("gl_PointSize = pointSize;");l.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return l.push("gl_Position = clipPos;"),l.push("}"),l}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ri=new e({}),Ui=d.vec3(),Li=function(e,t){this.id=Ri.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Si(t),this._allocate(t)},ki={};Li.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=ki[t];return i||(i=new Li(t,e),ki[t]=i,g.memory.programs++),i._useCount++,i},Li.prototype.put=function(){0==--this._useCount&&(Ri.removeItem(this.id),this._program&&this._program.destroy(),delete ki[this._hash],g.memory.programs--)},Li.prototype.webglContextRestored=function(){this._program=null},Li.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(A){const t=tt(i.dist,i.dir,A,Ui);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}if(n.id!==this._lastMaterialId){const t=n.fillColor,i=n.backfaces;e.backfaces!==i&&(i?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=i),o.uniform4f(this._uFillColor,t[0],t[1],t[2],n.fillAlpha),this._lastMaterialId=n.id}o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),o.uniform3fv(this._uOffset,a.offset),l.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(l.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(l.normalsBuf),e.bindArray++),l.indicesBuf?(l.indicesBuf.bind(),e.bindArray++):l.positionsBuf,this._lastGeometryId=l.id),l.indicesBuf?(o.drawElements(l.primitive,l.indicesBuf.numItems,l.indicesBuf.itemType,0),e.drawElements++):l.positionsBuf&&(o.drawArrays(o.TRIANGLES,0,l.positionsBuf.numItems),e.drawArrays++)},Li.prototype._allocate=function(e){const t=e.scene,i=t._lightsState,s=t._sectionPlanesState,r=t.canvas.gl;if(this._program=new Ci(r,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const o=this._program;this._uPositionsDecodeMatrix=o.getLocation("positionsDecodeMatrix"),this._uModelMatrix=o.getLocation("modelMatrix"),this._uModelNormalMatrix=o.getLocation("modelNormalMatrix"),this._uViewMatrix=o.getLocation("viewMatrix"),this._uViewNormalMatrix=o.getLocation("viewNormalMatrix"),this._uProjMatrix=o.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=i.lights.length;e<t;e++){switch(i.lights[e].type){case"ambient":this._uLightAmbient[e]=o.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=o.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=o.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=o.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)this._uSectionPlanes.push({active:o.getLocation("sectionPlaneActive"+e),pos:o.getLocation("sectionPlanePos"+e),dir:o.getLocation("sectionPlaneDir"+e)});this._uFillColor=o.getLocation("fillColor"),this._aPosition=o.getAttribute("position"),this._aNormal=o.getAttribute("normal"),this._uClippable=o.getLocation("clippable"),this._uGammaFactor=o.getLocation("gammaFactor"),this._uOffset=o.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=o.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Li.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t._lightsState,r=t.camera,o=r.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,i.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.normalMatrix),i.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];this._uLightAmbient[e]?i.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor)};class Oi{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),n.push("uniform vec3 scale;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = scale[0];"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = scale[1];"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ni=new e({}),Vi=d.vec3(),Qi=function(e,t){this.id=Ni.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Oi(t),this._allocate(t)},Hi={};Qi.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Hi[t];return i||(i=new Qi(t,e),Hi[t]=i,g.memory.programs++),i._useCount++,i},Qi.prototype.put=function(){0==--this._useCount&&(Ni.removeItem(this.id),this._program&&this._program.destroy(),delete Hi[this._hash],g.memory.programs--)},Qi.prototype.webglContextRestored=function(){this._program=null},Qi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(a.originHash,c):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(c){const t=tt(i.dist,i.dir,c,Vi);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}switch(i){case 0:n=t._xrayMaterial._state;break;case 1:n=t._highlightMaterial._state;break;case 2:n=t._selectedMaterial._state;break;default:n=t._edgeMaterial._state}if(n.id!==this._lastMaterialId){const t=n.backfaces;if(e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t),e.lineWidth!==n.edgeWidth&&(o.lineWidth(n.edgeWidth),e.lineWidth=n.edgeWidth),this._uEdgeColor){const e=n.edgeColor,t=n.edgeAlpha;o.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=n.id}let h;o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),o.uniform3fv(this._uOffset,a.offset),A.primitive===o.TRIANGLES?h=l._getEdgeIndices():A.primitive===o.LINES&&(h=A.indicesBuf),h&&(A.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,A.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(A.positionsBuf,A.compressGeometry?o.UNSIGNED_SHORT:o.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=A.id),o.drawElements(o.LINES,h.numItems,h.itemType,0),e.drawElements++)},Qi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program=new Ci(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+e),pos:r.getLocation("sectionPlanePos"+e),dir:r.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=r.getLocation("edgeColor"),this._aPosition=r.getAttribute("position"),this._uClippable=r.getLocation("clippable"),this._uGammaFactor=r.getLocation("gammaFactor"),this._uOffset=r.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Qi.prototype._bindProgram=function(e){const t=this._program,i=this._scene,s=i.canvas.gl,r=i.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)};class ji{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),n.push("uniform vec3 scale;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = scale[0];"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = scale[1];"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const Gi=d.vec3(),zi=function(e,t){this._hash=e,this._shaderSource=new ji(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Wi={};zi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Wi[t];if(!i){if(i=new zi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Wi[t]=i,g.memory.programs++}return i._useCount++,i},zi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Wi[this._hash],g.memory.programs--)},zi.prototype.webglContextRestored=function(){this._program=null},zi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(a){const t=tt(i.dist,i.dir,a,Gi);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}if(o.id!==this._lastMaterialId){const t=o.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=o.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=o.id}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),n.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),n.indicesBuf&&(n.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=n.id);var l=t._state.pickID;const A=l>>24&255,c=l>>16&255,h=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,h/255,c/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},zi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ci(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uPickColor=s.getLocation("pickColor"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},zi.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class Xi{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e<i.getNumAllocatedSectionPlanes();e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0;e<i.getNumAllocatedSectionPlanes();e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Ki=d.vec3(),Zi=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Xi(t),this._allocate(t)},Ji={};Zi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Ji[t];if(!i){if(i=new Zi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ji[t]=i,g.memory.programs++}return i._useCount++,i},Zi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ji[this._hash],g.memory.programs--)},Zi.prototype.webglContextRestored=function(){this._program=null},Zi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,c=o.frontface,h=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(l){const t=tt(i.dist,i.dir,l,Ki);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.logarithmicDepthBufferEnabled&&s.uniform1f(this._uZFar,i.camera.project.far),e.backfaces!==A&&(A?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=A),e.frontface!==c&&(c?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=c),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,a.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(u,a.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT)):this._aPosition.bindArrayBuffer(u),s.uniform2fv(this._uPickClipPos,e.pickClipPos),d.bind(),s.enableVertexAttribArray(this._aColor.location),s.vertexAttribPointer(this._aColor.location,d.itemSize,d.itemType,!0,0,0),s.drawArrays(a.primitive,0,u.numItems/3)},Zi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ci(i,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))};class Yi{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),n.push("uniform vec3 scale;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = scale[0];"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = scale[1];"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const qi=d.vec3(),$i=function(e,t){this._hash=e,this._shaderSource=new Yi(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},es={};$i.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=es[t];if(!i){if(i=new $i(t,e),i.errors)return console.log(i.errors.join("\n")),null;es[t]=i,g.memory.programs++}return i._useCount++,i},$i.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete es[this._hash],g.memory.programs--)},$i.prototype.webglContextRestored=function(){this._program=null},$i.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(a){const t=tt(i.dist,i.dir,a,qi);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}s.uniformMatrix4fv(this._uProjMatrix,!1,l._project._state.matrix),s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),n.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),n.indicesBuf&&(n.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=n.id),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},$i.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ci(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},$i.prototype._bindProgram=function(e){const t=this._scene,i=t.camera.project,s=t.canvas.gl;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class ts{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("vec4 encodeFloat( const in float depth ) {"),r.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),r.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),r.push(" vec4 comp = fract(depth * bitShift);"),r.push(" comp -= comp.xxyz * bitMask;"),r.push(" return comp;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const is=function(e,t){this._hash=e,this._shaderSource=new ts(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ss={};is.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=ss[i];if(!s){if(s=new is(i,e),s.errors)return console.log(s.errors.join("\n")),null;ss[i]=s,g.memory.programs++}return s._useCount++,s},is.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ss[this._hash],g.memory.programs--)},is.prototype.webglContextRestored=function(){this._program=null},is.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},is.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ci(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},is.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,i.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),i.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.getNumAllocatedSectionPlanes()>0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a<l;a++)e=this._uSectionPlanes[a],t=e.active,r=s.sectionPlanes[a],t&&i.uniform1i(t,r.active),o=e.pos,o&&i.uniform3fv(e.pos,r.pos),n=e.dir,n&&i.uniform3fv(e.dir,r.dir)}};class rs{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 os=d.OBB3(),ns=d.vec4(),as=d.vec4(),ls=d.vec4(),As=d.vec3([1,0,0]),cs=d.vec3([0,1,0]),hs=d.vec3([0,0,1]),us=d.vec3(3),ds=d.vec3(3),ps=d.identityMat4();class fs extends R{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new rs,this._state=new ae({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:"",pickHash:"",offset:d.vec3(),origin:null,originHash:null,isUI:t.isUI}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,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 i=t.origin||t.rtcCenter;if(i&&(this._state.origin=d.vec3(i),this._state.originHash=i.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||ps),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._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=Ti.get(this),this._emphasisFillRenderer=Li.get(this),this._emphasisEdgesRenderer=Qi.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=zi.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=$i.get(this))}}_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}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),i.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){d.transformOBB3(e,this._geometry.obb,os),d.OBB3ToAABB3(os,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 ns[0]=e[0],ns[1]=e[1],ns[2]=e[2],ns[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(ns,as),d.mulQuaternions(this.quaternion,as,ls),this.quaternion=ls,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return ns[0]=e[0],ns[1]=e[1],ns[2]=e[2],ns[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(ns,as),d.mulQuaternions(as,this.quaternion,as),this}rotateX(e){return this.rotate(As,e)}rotateY(e){return this.rotate(cs,e)}rotateZ(e){return this.rotate(hs,e)}translate(e,t){return d.vec3ApplyQuaternion(this.quaternion,e,us),d.mulVec3Scalar(us,t,ds),d.addVec3(this.position,ds,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(As,e)}translateY(e){return this.translate(cs,e)}translateZ(e){return this.translate(hs,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||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._drawRenderer||(this._drawRenderer=Ti.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=Ti.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Li.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Li.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Li.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qi.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qi.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qi.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qi.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Qi.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=$i.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=is.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=zi.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=Zi.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,i,s){ms(this,e,t,i,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),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 ms=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),o=d.vec3(),n=d.vec4(),a=d.vec3(),l=d.vec3(),A=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),m=d.vec3(),g=d.vec4(),_=d.vec4(),v=d.vec4(),b=d.vec3(),y=d.vec3(),w=d.vec3(),B=d.vec3(),P=d.vec3(),x=d.vec3(),C=d.vec3(),M=d.vec3(),E=d.vec3(),F=d.vec3(),I=d.vec3();return function(T,D,S,R,U){var L=U.primIndex;if(null!=L&&L>-1){const V=T.geometry._state,Q=T.scene,H=Q.camera,j=Q.canvas;if("triangles"===V.primitiveName){U.primitive="triangle";const Q=L,G=V.indices,z=V.positions;let W,X,K;if(G){var k=G[Q+0],O=G[Q+1],N=G[Q+2];o[0]=k,o[1]=O,o[2]=N,U.indices=o,W=3*k,X=3*O,K=3*N}else W=3*Q,X=W+3,K=X+3;if(i[0]=z[W+0],i[1]=z[W+1],i[2]=z[W+2],s[0]=z[X+0],s[1]=z[X+1],s[2]=z[X+2],r[0]=z[K+0],r[1]=z[K+1],r[2]=z[K+2],V.compressGeometry){const e=V.positionsDecodeMatrix;e&&(me.decompressPosition(i,e,i),me.decompressPosition(s,e,s),me.decompressPosition(r,e,r))}U.canvasPos?d.canvasPosToLocalRay(j.canvas,T.origin?Ye(D,T.origin):D,S,R,T.worldMatrix,U.canvasPos,e,t):U.origin&&U.direction&&d.worldRayToLocalRay(T.worldMatrix,U.origin,U.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,n),U.localPos=n,U.position=n,g[0]=n[0],g[1]=n[1],g[2]=n[2],g[3]=1,d.transformVec4(T.worldMatrix,g,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],U.canvasPos&&T.origin&&(a[0]+=T.origin[0],a[1]+=T.origin[1],a[2]+=T.origin[2]),U.worldPos=a,d.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],U.viewPos=l,d.cartesianToBarycentric(n,i,s,r,A),U.bary=A;const Z=V.normals;if(Z){if(V.compressGeometry){const e=3*k,t=3*O,i=3*N;me.decompressNormal(Z.subarray(e,e+2),c),me.decompressNormal(Z.subarray(t,t+2),h),me.decompressNormal(Z.subarray(i,i+2),u)}else c[0]=Z[W],c[1]=Z[W+1],c[2]=Z[W+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,A[0],b),d.mulVec3Scalar(h,A[1],y),w),d.mulVec3Scalar(u,A[2],B),P);U.worldNormal=d.normalizeVec3(d.transformVec3(T.worldNormalMatrix,e,x))}const J=V.uv;if(J){if(p[0]=J[2*k],p[1]=J[2*k+1],f[0]=J[2*O],f[1]=J[2*O+1],m[0]=J[2*N],m[1]=J[2*N+1],V.compressGeometry){const e=V.uvDecodeMatrix;e&&(me.decompressUV(p,e,p),me.decompressUV(f,e,f),me.decompressUV(m,e,m))}U.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(p,A[0],C),d.mulVec2Scalar(f,A[1],M),E),d.mulVec2Scalar(m,A[2],F),I)}}}}}();class gs extends R{get type(){return"Material"}constructor(e,t={}){super(e,t),g.memory.materials++}destroy(){super.destroy(),g.memory.materials--}}const _s={opaque:0,mask:1,blend:2},vs=["opaque","mask","blend"];class bs extends gs{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new ae({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=_s[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 vs[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 ys(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 ws(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=ys(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=ys(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=ys(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=ys(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){const t=ys(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=ys(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=ys(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 Bs=new Uint8Array([0,0,0,1]);class Ps{constructor({gl:e,target:t,format:i,type:s,wrapS:r,wrapT:o,wrapR:n,encoding:a,preloadColor:l,premultiplyAlpha:A,flipY:c}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=i||1023,this.type=s||1009,this.internalFormat=null,this.premultiplyAlpha=!!A,this.flipY=!!c,this.unpackAlignment=4,this.wrapS=r||1e3,this.wrapT=o||1e3,this.wrapR=n||1e3,this.encoding=a||3001,this.texture=e.createTexture(),l&&this.setPreloadColor(l),this.allocated=!0}setPreloadColor(e){e?(Bs[0]=Math.floor(255*e[0]),Bs[1]=Math.floor(255*e[1]),Bs[2]=Math.floor(255*e[2]),Bs[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Bs[0]=0,Bs[1]=0,Bs[2]=0,Bs[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,Bs)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Bs);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 o=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const n=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);const a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const l=ws(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(s=!0);const A=ws(i,this.magFilter);A&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,A);const c=ws(i,this.wrapS);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,c);const h=ws(i,this.wrapT);h&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,h);const u=ws(i,this.format,this.encoding),d=ws(i,this.type),p=xs(i,this.internalFormat,u,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(y.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,p,u,d,t[e])}}else i.texImage2D(i.TEXTURE_2D,0,p,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,o),i.pixelStorei(i.UNPACK_ALIGNMENT,n),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,a)}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 o=ws(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=ws(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ws(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,Cs(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Cs(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ws(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ws(i,this.magFilter)));const a=ws(i,this.format,this.encoding),l=ws(i,this.type),A=xs(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t<s;t++){const s=e[t];1023!==this.format?null!==a?i.compressedTexSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,a,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,a,l,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=ws(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=ws(t,e.magFilter);i&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,i))}if(void 0!==e.wrapS){const i=ws(t,e.wrapS);i&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,i))}if(void 0!==e.wrapT){const i=ws(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 xs(e,t,i,s,r,o=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let n=i;return i===e.RED&&(s===e.FLOAT&&(n=e.R32F),s===e.HALF_FLOAT&&(n=e.R16F),s===e.UNSIGNED_BYTE&&(n=e.R8)),i===e.RG&&(s===e.FLOAT&&(n=e.RG32F),s===e.HALF_FLOAT&&(n=e.RG16F),s===e.UNSIGNED_BYTE&&(n=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(n=e.RGBA32F),s===e.HALF_FLOAT&&(n=e.RGBA16F),s===e.UNSIGNED_BYTE&&(n=3001===r&&!1===o?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(n=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(n=e.RGB5_A1)),n!==e.R16F&&n!==e.R32F&&n!==e.RG16F&&n!==e.RG32F&&n!==e.RGBA16F&&n!==e.RGBA32F||ys(e,"EXT_color_buffer_float"),n}function Cs(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Ms(e){if(!Es(e.width)||!Es(e.height)){const t=document.createElement("canvas");t.width=Fs(e.width),t.height=Fs(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Es(e){return 0==(e&e-1)}function Fs(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Is extends R{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new ae({texture:new Ps({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),g.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}_webglContextRestored(){this._state.texture=new Ps({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_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=Ms(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=Ms(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(),g.memory.textures--}}const Ts=d.vec3(),Ds=d.vec3();d.vec3();const Ss=d.vec3([0,-1,0]),Rs=d.vec4([0,0,0,1]);class Us extends R{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 Is(this),this._plane=new fs(this,{geometry:new ve(this,Te({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new bs(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 fs(this,{geometry:new ve(this,Ie({size:1,divisions:10})),material:new bs(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]),qe(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,Ts);const s=-d.dotVec3(i,Ts);d.normalizeVec3(i),d.mulVec3Scalar(i,s,Ds),d.vec3PairToQuaternion(Ss,e,Rs),this._node.quaternion=Rs}}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 Ls extends gs{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new ae({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 ks={opaque:0,mask:1,blend:2},Os=["opaque","mask","blend"];class Ns extends gs{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new ae({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=ks[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 Os[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 Vs={opaque:0,mask:1,blend:2},Qs=["opaque","mask","blend"];class Hs extends gs{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new ae({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=Vs[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 Qs[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 js={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 Gs extends gs{get type(){return"EmphasisMaterial"}get presets(){return js}constructor(e,t={}){super(e,t),this._state=new ae({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=js[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(js).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 zs={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 Ws extends gs{get type(){return"EdgeMaterial"}get presets(){return zs}constructor(e,t={}){super(e,t),this._state=new ae({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=zs[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(zs).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}class Xs extends R{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new ae({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 Ks extends R{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 Is(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 fs(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new ve(this,Te({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new bs(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 Zs=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let o=0;o<3;o++)if(s=t[3*e+o],r=t[3*i+o],s!==r)return r-s;return 0}let o=e.slice().sort(r),n=null;for(let e=0,t=o.length;e<t;e++)0!==e&&0===r(o[e],o[e-1])||(n=o[e]),i[o[e]]=n;for(let t=0,r=e.length;t<r;t+=3){const r=i[e[t]],o=i[e[t+1]],n=i[e[t+2]];let a=r,l=o,A=n;if(r>o&&r>n?o>n?(a=r,l=o,A=n):(a=r,l=n,A=o):o>r&&o>n?r>n?(a=o,l=r,A=n):(a=o,l=n,A=r):n>r&&n>o&&(r>o?(a=n,l=r,A=o):(a=n,l=o,A=r)),s[t+0]=[a,l],s[t+1]=[l,A],a>A){const e=A;A=a,a=e}s[t+2]=[A,a]}function a(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(a);let l=0;for(let e=0;e<s.length;e++)if(0===e||0!==a(s[e],s[e-1])){if(0!==e&&2!==l)return!1;l=1}else l++;return!(s.length>0&&2!==l)},Js=d.vec3(),Ys=d.vec3(),qs=d.vec3();class $s{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&&!Zs(t,e))return-1;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],o=3*t[s+1],n=3*t[s+2];Js[0]=e[r],Js[1]=e[r+1],Js[2]=e[r+2],Ys[0]=e[o],Ys[1]=e[o+1],Ys[2]=e[o+2],qs[0]=e[n],qs[1]=e[n+1],qs[2]=e[n+2],d.cross3Vec3(Js,Ys,Js),i+=d.dotVec3(Js,qs)}return i/6}}const er=new $s,tr=d.vec3(),ir=d.vec3(),sr=d.vec3(),rr=d.vec3(),or=d.vec3(),nr=d.vec3();class ar{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],o=3*t[s+1],n=3*t[s+2];tr[0]=e[r],tr[1]=e[r+1],tr[2]=e[r+2],ir[0]=e[o],ir[1]=e[o+1],ir[2]=e[o+2],sr[0]=e[n],sr[1]=e[n+1],sr[2]=e[n+2],d.subVec3(tr,ir,rr),d.subVec3(sr,ir,or),i+=.5*d.lenVec3(d.cross3Vec3(rr,or,nr))}return i}}const lr=new ar,Ar=d.OBB3(),cr=d.OBB3(),hr=d.OBB3();class ur{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=d.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,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.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,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.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":er.reset(),er.setPrimitive(this.layer.primitive),this.getEachVertex((e=>{er.addVertex(e)})),this.getEachIndex((e=>{er.addIndex(e)})),this._volume=er.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":lr.reset(),this.getEachVertex((e=>{lr.addVertex(e)})),this.getEachIndex((e=>{lr.addIndex(e)})),this._surfaceArea=lr.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,Ar),this.transform?(d.transformOBB3(this.transform.worldMatrix,Ar,cr),d.transformOBB3(this.model.worldMatrix,cr,hr),d.OBB3ToAABB3(hr,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,Ar,cr),d.OBB3ToAABB3(cr,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const dr=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let pr=0;const fr=1,mr=4,gr=8,_r=16,vr=32,br=256,yr=512,wr=1024,Br=2048,Pr={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},xr=new Float32Array([1,1,1,1]),Cr=new Float32Array([0,0,0,1]),Mr=d.vec4(),Er=d.vec3(),Fr=d.vec3(),Ir=d.mat4();class Tr{constructor(e,t=!1,{instancing:i=!1,edges:s=!1,useAlphaCutoff:r=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._useAlphaCutoff=r,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t<o;t++){const r=this._uSectionPlanes[t];if(r)if(t<n){const o=A.sectionPlanesActivePerLayer[l+t];if(i.uniform1i(r.active,o?1:0),o){const o=a[t],n=e._state.origin;if(n){const e=tt(o.dist,o.dir,n,Er,s.matrix);i.uniform3fv(r.pos,e)}else i.uniform3fv(r.pos,o.pos);i.uniform3fv(r.dir,o.dir)}}else i.uniform1i(r.active,0)}}}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uColor||(this._uColor=s.getLocation("silhouetteColor")),this._uUVDecodeMatrix=s.getLocation("uvDecodeMatrix"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uGammaFactor=s.getLocation("gammaFactor"),t.uniformBlockBinding(s.handle,t.getUniformBlockIndex(s.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=s.getLocation("zFar")),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aUV=s.getAttribute("uv"),this._aColor=s.getAttribute("color"),this._aMetallicRoughness=s.getAttribute("metallicRoughness"),this._aFlags=s.getAttribute("flags"),this._aPickColor=s.getAttribute("pickColor"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrix=s.getAttribute("modelMatrix"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=s.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=s.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=s.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),this._useAlphaCutoff&&(this._alphaCutoffLocation=s.getLocation("materialAlphaCutoff")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=s.getLocation("intensityRange")),this._uPointSize=s.getLocation("pointSize"),this._uNearPlaneHeight=s.getLocation("nearPlaneHeight"),e.crossSections&&(this._uSliceColor=s.getLocation("sliceColor"),this._uSliceThickness=s.getLocation("sliceThickness"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState,o=r.lights;s.bind(),e.textureUnit=0,this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,r.getAmbientColorAndIntensity()),this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor);for(let e=0,t=o.length;e<t;e++){const t=o[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}}_makeVAO(e){const t=this._scene.canvas.gl,i=t.createVertexArray();return t.bindVertexArray(i),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer(e.positionsBuf),this._aUV&&this._aUV.bindArrayBuffer(e.uvBuf),this._aNormal&&this._aNormal.bindArrayBuffer(e.normalsBuf),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer(e.colorsBuf),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges&&e.edgeIndicesBuf?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),i}drawLayer(e,t,i,{colorUniform:s=!1,incrementDrawState:r=!1}={}){const o=Mi.MAX_TEXTURE_IMAGE_UNITS,n=this._scene,a=n.canvas.gl,{_state:l,model:A}=t,{textureSet:c,origin:h,positionsDecodeMatrix:u}=l,p=n._lightsState,f=n.pointsMaterial,{camera:m}=A.scene,{viewNormalMatrix:g,project:_}=m,v=e.pickViewMatrix||m.viewMatrix,{position:b,rotationMatrix:y,worldNormalMatrix:w}=A;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?a.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));let B=0;const P=16;this._matricesUniformBlockBufferData.set(y,0);const x=0!==h[0]||0!==h[1]||0!==h[2],C=0!==b[0]||0!==b[1]||0!==b[2];if(x||C){const e=Er;if(x){const t=d.transformPoint3(y,h,Fr);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=b[0],e[1]+=b[1],e[2]+=b[2],this._matricesUniformBlockBufferData.set(Ye(v,e,Ir),B+=P)}else this._matricesUniformBlockBufferData.set(v,B+=P);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||_.matrix,B+=P),this._matricesUniformBlockBufferData.set(u,B+=P),this._matricesUniformBlockBufferData.set(w,B+=P),this._matricesUniformBlockBufferData.set(g,B+=P),a.bindBuffer(a.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),a.bufferData(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,a.DYNAMIC_DRAW),a.bindBufferBase(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),a.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),n.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&a.uniform1f(this._uZFar,n.camera.project.far)}if(this._uPickInvisible&&a.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&a.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&a.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&a.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&a.uniform2f(this._uDrawingBufferSize,a.drawingBufferWidth,a.drawingBufferHeight),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._uIntensityRange&&f.filterIntensity&&a.uniform2f(this._uIntensityRange,f.minIntensity,f.maxIntensity),this._uPointSize&&a.uniform1f(this._uPointSize,f.pointSize),this._uNearPlaneHeight){const e="ortho"===n.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*n.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,e)}if(c){const{colorTexture:t,metallicRoughnessTexture:i,emissiveTexture:s,normalsTexture:r,occlusionTexture:n}=c;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uMetallicRoughMap&&i&&(this._program.bindTexture(this._uMetallicRoughMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uEmissiveMap&&s&&(this._program.bindTexture(this._uEmissiveMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uNormalMap&&r&&(this._program.bindTexture(this._uNormalMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uAOMap&&n&&(this._program.bindTexture(this._uAOMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o)}if(p.reflectionMaps.length>0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;Mr[0]=i,Mr[1]=s,Mr[2]=t.blendCutoff,Mr[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Mr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(this._useAlphaCutoff&&a.uniform1f(this._alphaCutoffLocation,c.alphaCutoff),s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Pr[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Pr[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Pr[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?Cr:xr)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,g.memory.programs--}}class Dr extends Tr{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!1,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)i.edgeIndicesBuf&&t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Sr extends Dr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++)r=i.lights[e],"ambient"!==r.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===r.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")));o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.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);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e<t;e++)if(r=i.lights[e],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?o.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return o.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),o.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;")),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?(s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;")):(s.push(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Rr extends Dr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";");r.push("uniform float sliceThickness;"),r.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;");for(let e=0,i=t.lights.length;e<i;e++){const i=t.lights[e];"ambient"!==i.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec4 newColor;"),r.push(" newColor = vColor;"),s){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e<i;e++){const i=t.lights[e];if("ambient"!==i.type){if("dir"===i.type)"view"===i.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?r.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled?r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(r.push(" float dx = dFdx(gl_FragCoord.z);"),r.push(" float dy = dFdy(gl_FragCoord.z);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = gl_FragCoord.z + diff;")),r.push("}"),r}}class Ur extends Dr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");o.push("uniform float sliceThickness;"),o.push("uniform vec4 sliceColor;")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),o.push(" vec4 newColor;"),o.push(" newColor = vColor;"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class Lr extends Dr{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class kr extends Lr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Or extends Lr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Nr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Vr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Qr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Hr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push(" if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class jr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec2 vHighPrecisionZW;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class Gr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class zr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 encodeFloat( const in float v ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(v * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class Wr extends Dr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.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);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),o&&n.push("in vec4 vClipPosition;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),n.push(" return surf_norm;"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");o?(n.push(" if (dist > (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),n.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return n.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),n.push("float aoFactor = texture(uAOMap, vUV).r;"),n.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),n.push("vec4 fragColor;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):n.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&n.push("fragColor = linearToGamma(fragColor, gammaFactor);"),n.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Xr extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Kr extends Dr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(o&&n.push("uniform float materialAlphaCutoff;"),n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return n.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),n.push("vec4 sampleColor = texture(uColorMap, vUV);"),o&&(n.push("if (sampleColor.a < materialAlphaCutoff) {"),n.push(" discard;"),n.push("}")),t&&n.push("sampleColor = sRGBToLinear(sampleColor);"),n.push("vec4 colorTexel = color * sampleColor;"),n.push("float opacity = color.a;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):n.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&n.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}const Zr=d.vec3(),Jr=d.vec3(),Yr=d.vec3(),qr=d.vec3(),$r=d.mat4();class eo extends Tr{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Zr;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Jr;if(l){const e=Yr;d.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,$r),m=qr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const to=d.vec3(),io=d.vec3(),so=d.vec3(),ro=d.vec3(),oo=d.mat4();class no extends Tr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=to;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=io;if(l){const e=so;d.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,oo),m=ro,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ao{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ur(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Nr(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Vr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new eo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new no(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Sr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Sr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Rr(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Rr(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Kr(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Kr(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Kr(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Kr(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Wr(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Wr(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ur(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new jr(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Gr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new kr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Or(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Nr(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Qr(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Xr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Hr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new zr(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new no(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new eo(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const lo={};let Ao=65536,co=5e6;class ho{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),Ao=e}get maxDataTextureHeight(){return Ao}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),co=e}get maxGeometryBatchSize(){return co}}const uo=new ho;class po{constructor(e=uo.maxGeometryBatchSize){this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const fo=d.mat4(),mo=d.mat4();function go(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,c=t[5]-a,h=65525,u=h/l,p=h/A,f=h/c,m=e=>e>=0?e:0;for(let t=0;t<s;t+=3)r[t+0]=Math.floor(m(e[t+0]-o)*u),r[t+1]=Math.floor(m(e[t+1]-n)*p),r[t+2]=Math.floor(m(e[t+2]-a)*f);return d.identityMat4(fo),d.translationMat4v(t,fo),d.identityMat4(mo),d.scalingMat4v([l/h,A/h,c/h],mo),d.mulMat4(fo,mo,i),r}function _o(e,t){const i=e[0],s=e[1],r=e[2],o=e[3]-i,n=e[4]-s,a=e[5]-r,l=65525;return d.identityMat4(fo),d.translationMat4v(e,fo),d.identityMat4(mo),d.scalingMat4v([o/l,n/l,a/l],mo),d.mulMat4(fo,mo,t),t}function vo(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 bo(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 yo=d.mat4(),wo=d.mat4(),Bo=d.vec4([0,0,0,1]),Po=d.vec3(),xo=d.vec3(),Co=d.vec3(),Mo=d.vec3(),Eo=d.vec3(),Fo=d.vec3(),Io=d.vec3();class To{constructor(e){this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=lo[t];return i||(i=new ao(e),lo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete lo[t],i._destroy()}))),i}(e.model.scene),this._buffer=new po(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new ae({origin:d.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=d.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=d.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid,this.primitive=e.primitive}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}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=t.positions,s=t.positionsCompressed,r=t.normals,o=t.normalsCompressed,n=t.uv,a=t.uvCompressed,l=t.colors,A=t.colorsCompressed,c=t.indices,h=t.edgeIndices,u=t.color,p=t.metallic,f=t.roughness,m=t.opacity,g=t.meshMatrix,_=t.pickColor,v=this.model.scene,b=this._buffer,y=b.positions.length/3;let w;if(d.expandAABB3(this._modelAABB,t.aabb),this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";w=s.length/3;for(let e=0,t=s.length;e<t;e++)b.positions.push(s[e])}else{if(!i)throw"positions expected";w=i.length/3;for(let e=0,t=i.length;e<t;e++)b.positions.push(i[e])}if(o&&o.length>0)for(let e=0,t=o.length;e<t;e++)b.normals.push(o[e]);else if(r&&r.length>0){const e=yo;g?d.inverseMat4(d.transposeMat4(g,wo),e):d.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,c,h,u=new Float32Array([0,0,0,0]),p=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,p),d.normalizeVec3(p,p),l=n=vo(p,"floor","floor"),a=bo(n),A=c=o(p,a),n=vo(p,"ceil","floor"),a=bo(n),A=o(p,a),A>c&&(l=n,c=A),n=vo(p,"floor","ceil"),a=bo(n),A=o(p,a),A>c&&(l=n,c=A),n=vo(p,"ceil","ceil"),a=bo(n),A=o(p,a),A>c&&(l=n,c=A),s[r+h+0]=l[0],s[r+h+1]=l[1],s[r+h+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)b.colors.push(255*l[e]),b.colors.push(255*l[e+1]),b.colors.push(255*l[e+2]),b.colors.push(255);else if(A)for(let e=0,t=l.length;e<t;e+=3)b.colors.push(l[e]),b.colors.push(l[e+1]),b.colors.push(l[e+2]),b.colors.push(255);else if(u){const e=u[0],t=u[1],i=u[2],s=m;for(let r=0;r<w;r++)b.colors.push(e),b.colors.push(t),b.colors.push(i),b.colors.push(s)}const B=null!=p?p:0,P=null!=f?f:255;for(let e=0;e<w;e++)b.metallicRoughness.push(B),b.metallicRoughness.push(P);if(n&&n.length>0)for(let e=0,t=n.length;e<t;e++)b.uv.push(n[e]);else if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)b.uv.push(a[e]);for(let e=0,t=c.length;e<t;e++)b.indices.push(y+c[e]);if(h)for(let e=0,t=h.length;e<t;e++)b.edgeIndices.push(y+h[e]);{const e=b.pickColors.length;for(let t=e,i=e+4*w;t<i;t+=4)b.pickColors.push(_[0]),b.pickColors.push(_[1]),b.pickColors.push(_[2]),b.pickColors.push(_[3])}if(v.entityOffsetsEnabled)for(let e=0;e<w;e++)b.offsets.push(0),b.offsets.push(0),b.offsets.push(0);const x=this._portions.length,C={vertsBaseIndex:y,numVerts:w,indicesBaseIndex:b.indices.length-c.length,numIndices:c.length};return v.readableGeometryEnabled&&(C.indices=c,v.entityOffsetsEnabled&&(C.offset=new Float32Array(3))),this._portions.push(C),this._numPortions++,this.model.numPortions++,this._numVerts+=C.numVerts,this._meshes.push(e),x}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):go(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=d.mat4());if(e.positionsBuf=new le(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],i=3*t.vertsBaseIndex,r=i+3*t.numVerts;t.quantizedPositions=s.slice(i,r)}}if(i.normals.length>0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new le(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new le(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new le(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=me.getUVBounds(i.uv),r=me.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=d.mat3(r.decodeMatrix),e.uvBuf=new le(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new le(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new le(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new le(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new le(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new le(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new le(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Br&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Br?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],c=t[3];for(let e=0;e<o;e+=4)n[e+0]=a,n[e+1]=l,n[e+2]=A,n[e+3]=c;this._state.colorsBuf&&this._state.colorsBuf.setData(n,r,o)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=e,o=this._portions[r],n=o.vertsBaseIndex,a=o.numVerts,l=!!(t&fr),A=!!(t&br),c=!!(t&yr),h=!!(t&wr),u=!!(t&Br),d=!!(t&gr),p=!!(t&mr);let f,m;f=!l||p||A||c&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,m=!l||p?Pr.NOT_RENDERED:h?Pr.SILHOUETTE_SELECTED:c?Pr.SILHOUETTE_HIGHLIGHTED:A?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let g=0;g=!l||p?Pr.NOT_RENDERED:h?Pr.EDGES_SELECTED:c?Pr.EDGES_HIGHLIGHTED:A?Pr.EDGES_XRAYED:u?i?Pr.EDGES_COLOR_TRANSPARENT:Pr.EDGES_COLOR_OPAQUE:Pr.NOT_RENDERED;let _=l&&!p&&d?Pr.PICK:Pr.NOT_RENDERED;const v=t&_r?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=n,t=n+a;e<t;e++){let t=0;t|=f,t|=m<<4,t|=g<<8,t|=_<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(a);for(let t=0;t<a;t++){let i=0;i|=f,i|=m<<4,i|=g<<8,i|=_<<12,i|=v<<16,e[t]=i}this._state.flagsBuf.setData(e,n,a)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=e,s=this._portions[i],r=3*s.vertsBaseIndex,o=3*s.numVerts,n=this._scratchMemory.getFloat32Array(o),a=t[0],l=t[1],A=t[2];for(let e=0;e<o;e+=3)n[e+0]=a,n[e+1]=l,n[e+2]=A;this._state.offsetsBuf&&this._state.offsetsBuf.setData(n,r,o),this.model.scene.readableGeometryEnabled&&(s.offset[0]=t[0],s.offset[1]=t[1],s.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portions[e];if(!s)return void this.model.error("portion not found: "+e);const r=s.quantizedPositions,o=this.model.matrix,n=d.vec4();n.set(i.origin,0),n[3]=1,d.mulMat4v4(o,n,n);const a=n[0],l=n[1],A=n[2],c=Bo,h=i.positionsDecodeMatrix;for(let e=0,i=r.length;e<i;e+=3)c[0]=r[e],c[1]=r[e+1],c[2]=r[e+2],c[3]=1,d.decompressPosition(c,h),c[3]=1,d.mulMat4v4(o,c,c),c[0]+=a,c[1]+=l,c[2]+=A,t(c)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const s=i.indices;for(let e=0,i=s.length;e<i;e++)t(s[e])}getElementsCountAndOffset(e){let t=null,i=null;const s=this._portions[e];return s&&(t=s.numIndices,i=s.indicesBaseIndex),{count:t,offset:i}}readGeometryData(e){if(!this._finalized)throw"Not finalized";const t=this._portions[e],i=this._state,s=this.model.matrix,r=i.positionsDecodeMatrix,o=d.vec4();o.set(i.origin,0),o[3]=1,d.mulMat4v4(s,o,o);const n=i.indicesBuf.getData(t.indicesBaseIndex,t.numIndices).map((e=>e-t.vertsBaseIndex)),a=d.mulMat4(s,r,new Array(16));a[12]+=o[0],a[13]+=o[1],a[14]+=o[2];const l=i.positionsBuf.getData(t.vertsBaseIndex,t.numVerts);return{indices:n,positions:d.transformPositions3(a,l,new Array(l.length))}}drawColorOpaque(e,t){if(this._numCulledLayerPortions===this._numPortions||0===this._numVisibleLayerPortions||this._numTransparentLayerPortions===this._numPortions||this._numXRayedLayerPortions===this._numPortions)return;this._updateBackfaceCull(e,t);const i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){if(this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions)if(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported)this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT);else if(t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported){this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,Pr.COLOR_TRANSPARENT):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT)}else this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT)}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Pr.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Pr.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Pr.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Pr.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,Pr.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Pr.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Pr.PICK))}precisionRayPickSurface(e,t,i,s,r){if(!this.model.scene.readableGeometryEnabled)return!1;const o=this._state,n=this._portions[e];if(!n)return this.model.error("portion not found: "+e),!1;const a=n.quantizedPositions,l=n.indices,A=o.origin,c=n.offset,h=Po,u=xo;h.set(A?d.subVec3(t,A,Co):t),u.set(i),c&&d.subVec3(h,c),d.transformRay(this.model.worldNormalMatrix,h,u,h,u);const p=Mo,f=Eo,m=Fo;let g=!1,_=0;const v=Io;for(let e=0,i=l.length;e<i;e+=3){const i=3*l[e],n=3*l[e+1],b=3*l[e+2];if(p[0]=a[i],p[1]=a[i+1],p[2]=a[i+2],f[0]=a[n],f[1]=a[n+1],f[2]=a[n+2],m[0]=a[b],m[1]=a[b+1],m[2]=a[b+2],d.decompressPosition(p,o.positionsDecodeMatrix),d.decompressPosition(f,o.positionsDecodeMatrix),d.decompressPosition(m,o.positionsDecodeMatrix),d.rayTriangleIntersect(h,u,p,f,m,v)){d.transformPoint3(this.model.worldMatrix,v,v),c&&d.addVec3(v,c),A&&d.addVec3(v,A);const e=Math.abs(d.lenVec3(d.subVec3(v,t,[])));(!g||e>_)&&(_=e,s.set(v),r&&d.triangleNormal(p,f,m,r),g=!0)}}return g&&r&&(d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),g}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Do extends Tr{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!0,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?i.edgeIndicesBuf&&t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class So extends Do{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r<o;r++)n=i.lights[r],"ambient"!==n.type&&(a.push("uniform vec4 lightColor"+r+";"),"dir"===n.type&&a.push("uniform vec3 lightDir"+r+";"),"point"===n.type&&a.push("uniform vec3 lightPos"+r+";"),"spot"===n.type&&(a.push("uniform vec3 lightPos"+r+";"),a.push("uniform vec3 lightDir"+r+";")));for(a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.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);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r<o;r++)if(n=i.lights[r],"ambient"!==n.type){if("dir"===n.type)"view"===n.space?a.push("viewLightDir = normalize(lightDir"+r+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);");else if("point"===n.type)"view"===n.space?a.push("viewLightDir = -normalize(lightPos"+r+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+r+", 0.0)).xyz);");else{if("spot"!==n.type)continue;"view"===n.space?a.push("viewLightDir = normalize(lightDir"+r+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+r+".rgb * lightColor"+r+".a);")}return a.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?(s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;")):(s.push(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Ro extends Do{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}for(this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;"),s=0,r=i.lights.length;s<r;s++){const e=i.lights[s];"ambient"!==e.type&&(n.push("uniform vec4 lightColor"+s+";"),"dir"===e.type&&n.push("uniform vec3 lightDir"+s+";"),"point"===e.type&&n.push("uniform vec3 lightPos"+s+";"),"spot"===e.type&&(n.push("uniform vec3 lightPos"+s+";"),n.push("uniform vec3 lightDir"+s+";")))}if(n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),o){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s<r;s++){const e=i.lights[s];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?n.push("viewLightDir = normalize(lightDir"+s+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+s+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?n.push("viewLightDir = -normalize(lightPos"+s+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+s+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?n.push("viewLightDir = normalize(lightDir"+s+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+s+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+s+".rgb * lightColor"+s+".a);")}}return n.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):n.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled?n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(n.push(" float dx = dFdx(gl_FragCoord.z);"),n.push(" float dy = dFdy(gl_FragCoord.z);"),n.push(" float diff = sqrt(dx*dx+dy*dy);"),n.push(" gl_FragDepth = gl_FragCoord.z + diff;")),n.push("}"),n}}class Uo extends Do{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class Lo extends Do{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class ko extends Lo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Oo extends Lo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class No extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Vo extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Qo extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Ho extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class jo extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("in vec2 vHighPrecisionZW;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class Go extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class zo extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Wo={3e3:"linearToLinear",3001:"sRGBToLinear"};class Xo extends Do{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.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);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),o&&n.push("in vec4 vClipPosition;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Wo[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Wo[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");o?(n.push(" if (dist > (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),n.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return n.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),n.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),n.push("vec4 fragColor;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):n.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&n.push("fragColor = linearToGamma(fragColor, gammaFactor);"),n.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Ko extends Do{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Zo extends Do{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(o&&n.push("uniform float materialAlphaCutoff;"),n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return n.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),n.push("vec4 sampleColor = texture(uColorMap, vUV);"),o&&(n.push("if (sampleColor.a < materialAlphaCutoff) {"),n.push(" discard;"),n.push("}")),t&&n.push("sampleColor = sRGBToLinear(sampleColor);"),n.push("vec4 colorTexel = color * sampleColor;"),n.push("float opacity = color.a;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):n.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&n.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}const Jo=d.vec3(),Yo=d.vec3(),qo=d.vec3(),$o=d.vec3(),en=d.mat4();class tn extends Tr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Jo;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Yo;if(l){const e=d.transformPoint3(c,l,qo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,en),m=$o,m[0]=n.eye[0]-t[0],m[1]=n.eye[1]-t[1],m[2]=n.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,m),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElementsInstanced(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sn=d.vec3(),rn=d.vec3(),on=d.vec3(),nn=d.vec3(),an=d.mat4();class ln extends Tr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=sn;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=rn;if(l){const e=d.transformPoint3(c,l,on);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,an),m=nn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class An{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Uo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new No(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Vo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new tn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ln(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new So(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new So(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Ro(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Ro(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Zo(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Zo(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Zo(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Zo(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Xo(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Xo(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Uo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new jo(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Go(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new ko(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Oo(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new No(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Qo(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ko(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ho(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new zo(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ln(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new tn(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const cn={};const hn=new Uint8Array(4),un=new Float32Array(1),dn=d.vec4([0,0,0,1]),pn=new Float32Array(3),fn=d.vec3(),mn=d.vec3(),gn=d.vec3(),_n=d.vec3(),vn=d.vec3(),bn=d.vec3(),yn=d.vec3(),wn=new Float32Array(4);class Bn{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=cn[t];return i||(i=new An(e),cn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete cn[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new ae({numInstances:0,obb:d.OBB3(),origin:d.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices,this.primitive=e.geometry.primitive}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}createPortion(e,t){const i=t.color,s=t.metallic,r=t.roughness,o=null!==t.opacity&&void 0!==t.opacity?t.opacity:255,n=t.meshMatrix,a=t.pickColor;if(this._finalized)throw"Already finalized";const l=i[0],A=i[1],c=i[2];if(this._colors.push(l),this._colors.push(A),this._colors.push(c),this._colors.push(o),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=r?r:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),this._state.geometry.normals){let e=d.transposeMat4(n,d.mat4()),t=d.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]),this._state.numInstances++;const h=this._portions.length,u={};return this.model.scene.readableGeometryEnabled&&(u.matrix=n.slice(),u.inverseMatrix=null,u.normalMatrix=null),this._portions.push(u),this._numPortions++,this.model.numPortions++,this._meshes.push(e),h}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,i=e.textureSet,s=this.model.scene.canvas.gl,r=this._colors.length,o=r/4;if(r>0){let t=!1;e.colorsBuf=new le(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new le(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new le(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new le(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new le(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=d.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new le(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new le(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new le(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),t.edgeIndices&&t.edgeIndices.length>0&&(e.edgeIndicesBuf=new le(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new le(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new le(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new le(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new le(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new le(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new le(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new le(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Br&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Br?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";hn[0]=t[0],hn[1]=t[1],hn[2]=t[2],hn[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(hn,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&fr),r=!!(t&br),o=!!(t&yr),n=!!(t&wr),a=!!(t&Br),l=!!(t&gr),A=!!(t&mr);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,h=!s||A?Pr.NOT_RENDERED:n?Pr.SILHOUETTE_SELECTED:o?Pr.SILHOUETTE_HIGHLIGHTED:r?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let u=0;u=!s||A?Pr.NOT_RENDERED:n?Pr.EDGES_SELECTED:o?Pr.EDGES_HIGHLIGHTED:r?Pr.EDGES_XRAYED:a?i?Pr.EDGES_COLOR_TRANSPARENT:Pr.EDGES_COLOR_OPAQUE:Pr.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?Pr.PICK:Pr.NOT_RENDERED)<<12,d|=(t&_r?1:0)<<16,un[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(un,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(pn[0]=t[0],pn[1]=t[1],pn[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(pn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.positionsCompressed,n=this.model.matrix,a=d.vec4();a.set(i.origin,0),a[3]=1,d.mulMat4v4(n,a,a);const l=a[0],A=a[1],c=a[2],h=dn,u=r.matrix,p=i.positionsDecodeMatrix;for(let e=0,i=o.length;e<i;e+=3)h[0]=o[e],h[1]=o[e+1],h[2]=o[e+2],d.decompressPosition(h,p),d.transformPoint3(u,h,h),h[3]=1,d.mulMat4v4(n,h,h),h[0]+=l,h[1]+=A,h[2]+=c,t(h)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state.geometry;if(!this._portions[e])return void this.model.error("portion not found: "+e);const s=i.indices;for(let e=0,i=s.length;e<i;e++)t(s[e])}setMatrix(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;wn[0]=t[0],wn[1]=t[4],wn[2]=t[8],wn[3]=t[12],this._state.modelMatrixCol0Buf.setData(wn,i),wn[0]=t[1],wn[1]=t[5],wn[2]=t[9],wn[3]=t[13],this._state.modelMatrixCol1Buf.setData(wn,i),wn[0]=t[2],wn[1]=t[6],wn[2]=t[10],wn[3]=t[14],this._state.modelMatrixCol2Buf.setData(wn,i)}readGeometryData(e){if(!this._finalized)throw"Not finalized";const t=this._state,i=this.model.matrix,s=t.modelMatrixCol0Buf.getData(e,1),r=t.modelMatrixCol1Buf.getData(e,1),o=t.modelMatrixCol2Buf.getData(e,1),n=[s[0],r[0],o[0],0,s[1],r[1],o[1],0,s[2],r[2],o[2],0,s[3],r[3],o[3],1],a=t.positionsDecodeMatrix,l=d.vec4();l.set(t.origin,0),l[3]=1,d.mulMat4v4(i,l,l);const A=t.indicesBuf.getData(),c=d.mulMat4(n,a,new Array(16));d.mulMat4(i,c,c),c[12]+=l[0],c[13]+=l[1],c[14]+=l[2];const h=t.positionsBuf.getData();return{indices:A,positions:d.transformPositions3(c,h,new Array(h.length))}}drawColorOpaque(e,t){if(this._numCulledLayerPortions===this._numPortions||0===this._numVisibleLayerPortions||this._numTransparentLayerPortions===this._numPortions||this._numXRayedLayerPortions===this._numPortions)return;this._updateBackfaceCull(e,t);const i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Pr.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Pr.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Pr.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Pr.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,Pr.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Pr.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Pr.PICK))}precisionRayPickSurface(e,t,i,s,r){if(!this.model.scene.readableGeometryEnabled)return!1;const o=this._state.geometry,n=this._state,a=this._portions[e];if(!a)return this.model.error("portion not found: "+e),!1;a.inverseMatrix||(a.inverseMatrix=d.inverseMat4(a.matrix,d.mat4())),r&&!a.normalMatrix&&(a.normalMatrix=d.transposeMat4(a.inverseMatrix,d.mat4()));const l=o.quantizedPositions,A=o.indices,c=n.origin,h=a.offset,u=fn,p=mn;u.set(c?d.subVec3(t,c,gn):t),p.set(i),h&&d.subVec3(u,h),d.transformRay(this.model.worldNormalMatrix,u,p,u,p),d.transformRay(a.inverseMatrix,u,p,u,p);const f=_n,m=vn,g=bn;let _=!1,v=0;const b=yn;for(let e=0,i=A.length;e<i;e+=3){const i=3*A[e+0],o=3*A[e+1],y=3*A[e+2];f[0]=l[i],f[1]=l[i+1],f[2]=l[i+2],m[0]=l[o],m[1]=l[o+1],m[2]=l[o+2],g[0]=l[y],g[1]=l[y+1],g[2]=l[y+2];const{positionsDecodeMatrix:w}=n.geometry;if(d.decompressPosition(f,w),d.decompressPosition(m,w),d.decompressPosition(g,w),d.rayTriangleIntersect(u,p,f,m,g,b)){d.transformPoint3(a.matrix,b,b),d.transformPoint3(this.model.worldMatrix,b,b),h&&d.addVec3(b,h),c&&d.addVec3(b,c);const e=Math.abs(d.lenVec3(d.subVec3(b,t,[])));(!_||e>v)&&(v=e,s.set(b),r&&d.triangleNormal(f,m,g,r),_=!0)}}return _&&r&&(d.transformVec3(a.normalMatrix,r,r),d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Pn extends Tr{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class xn extends Pn{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Cn extends Pn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Mn=d.vec3(),En=d.vec3(),Fn=d.vec3(),In=d.vec3(),Tn=d.mat4();class Dn extends Tr{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Mn;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=En;if(l){const e=Fn;d.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,Tn),m=In,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Sn=d.vec3(),Rn=d.vec3(),Un=d.vec3(),Ln=d.vec3(),kn=d.mat4();class On extends Tr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Sn;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Rn;if(l){const e=Un;d.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,kn),m=Ln,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Nn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new xn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Cn(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Dn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new On(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Vn={};class Qn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class Hn{constructor(e){this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Vn[t];return i||(i=new Nn(e),Vn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Vn[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new Qn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new ae({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin)),this.primitive=e.primitive}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}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=t.positions,s=t.positionsCompressed,r=t.indices,o=t.color,n=t.opacity,a=this._buffer,l=a.positions.length/3;let A;if(d.expandAABB3(this._modelAABB,t.aabb),this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";A=s.length/3;for(let e=0,t=s.length;e<t;e++)a.positions.push(s[e])}else{if(!i)throw"positions expected";A=i.length/3;for(let e=0,t=i.length;e<t;e++)a.positions.push(i[e])}if(o){const e=o[0],t=o[1],i=o[2],s=n;for(let r=0;r<A;r++)a.colors.push(e),a.colors.push(t),a.colors.push(i),a.colors.push(s)}if(r)for(let e=0,t=r.length;e<t;e++)a.indices.push(r[e]+l);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<A;e++)a.offsets.push(0),a.offsets.push(0),a.offsets.push(0);const c=this._portions.length/2;return this._portions.push(l),this._portions.push(A),this._numPortions++,this.model.numPortions++,this._numVerts+=A,this._meshes.push(e),c}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new le(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=go(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new le(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new le(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new le(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new le(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new le(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Br&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Br?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e<r;e+=4)o[e+0]=n,o[e+1]=a,o[e+2]=l,o[e+3]=A;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=2*e,o=this._portions[r],n=this._portions[r+1],a=!!(t&fr),l=!!(t&br),A=!!(t&yr),c=!!(t&wr),h=!!(t&gr),u=!!(t&mr);let d,p;d=!a||u||l||A&&!this.model.scene.highlightMaterial.glowThrough||c&&!this.model.scene.selectedMaterial.glowThrough?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,p=!a||u?Pr.NOT_RENDERED:c?Pr.SILHOUETTE_SELECTED:A?Pr.SILHOUETTE_HIGHLIGHTED:l?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let f=a&&!u&&h?Pr.PICK:Pr.NOT_RENDERED;const m=t&_r?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=o,t=o+n;e<t;e++){let t=0;t|=d,t|=p<<4,t|=f<<12,t|=m<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(n);for(let t=0;t<n;t++){let i=0;i|=d,i|=p<<4,i|=f<<12,i|=m<<16,e[t]=i}this._state.flagsBuf.setData(e,o,n)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Pr.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Pr.PICK)}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class jn extends Tr{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++}}class Gn extends jn{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class zn extends jn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Wn=d.vec3(),Xn=d.vec3(),Kn=d.vec3();d.vec3();const Zn=d.mat4();class Jn extends Tr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Wn;let f;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Xn;if(l){const e=d.transformPoint3(c,l,Kn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,Zn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yn=d.vec3(),qn=d.vec3(),$n=d.vec3();d.vec3();const ea=d.mat4();class ta extends Tr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Yn;let f;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=qn;if(l){const e=d.transformPoint3(c,l,$n);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,ea),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ia{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new Jn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ta(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Gn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new zn(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Jn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ta(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const sa={};const ra=new Uint8Array(4),oa=new Float32Array(1),na=new Float32Array(3),aa=new Float32Array(4);class la{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=sa[t];return i||(i=new ia(e),sa[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete sa[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new ae({obb:d.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=d.vec3(e.origin)),this._finalized=!1,this.primitive=e.primitive}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}createPortion(e,t){const i=t.color,s=t.opacity,r=t.meshMatrix;if(this._finalized)throw"Already finalized";const o=i[0],n=i[1],a=i[2];i[3],this._colors.push(o),this._colors.push(n),this._colors.push(a),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(r[0]),this._modelMatrixCol0.push(r[4]),this._modelMatrixCol0.push(r[8]),this._modelMatrixCol0.push(r[12]),this._modelMatrixCol1.push(r[1]),this._modelMatrixCol1.push(r[5]),this._modelMatrixCol1.push(r[9]),this._modelMatrixCol1.push(r[13]),this._modelMatrixCol2.push(r[2]),this._modelMatrixCol2.push(r[6]),this._modelMatrixCol2.push(r[10]),this._modelMatrixCol2.push(r[14]),this._state.numInstances++;const l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),l}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._state,i=t.geometry,s=this._colors.length,r=s/4;if(s>0){let t=!1;this._state.colorsBuf=new le(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new le(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new le(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new le(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=d.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new le(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Br&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Br?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";ra[0]=t[0],ra[1]=t[1],ra[2]=t[2],ra[3]=t[3],this._state.colorsBuf.setData(ra,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&fr),r=!!(t&br),o=!!(t&yr),n=!!(t&wr),a=!!(t&Br),l=!!(t&gr),A=!!(t&mr);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,h=!s||A?Pr.NOT_RENDERED:n?Pr.SILHOUETTE_SELECTED:o?Pr.SILHOUETTE_HIGHLIGHTED:r?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let u=0;u=!s||A?Pr.NOT_RENDERED:n?Pr.EDGES_SELECTED:o?Pr.EDGES_HIGHLIGHTED:r?Pr.EDGES_XRAYED:a?i?Pr.EDGES_COLOR_TRANSPARENT:Pr.EDGES_COLOR_OPAQUE:Pr.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?Pr.PICK:Pr.NOT_RENDERED)<<12,d|=(t&_r?1:0)<<16,oa[0]=d,this._state.flagsBuf.setData(oa,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(na[0]=t[0],na[1]=t[1],na[2]=t[2],this._state.offsetsBuf.setData(na,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;aa[0]=t[0],aa[1]=t[4],aa[2]=t[8],aa[3]=t[12],this._state.modelMatrixCol0Buf.setData(aa,i),aa[0]=t[1],aa[1]=t[5],aa[2]=t[9],aa[3]=t[13],this._state.modelMatrixCol1Buf.setData(aa,i),aa[0]=t[2],aa[1]=t[6],aa[2]=t[10],aa[3]=t[14],this._state.modelMatrixCol2Buf.setData(aa,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Pr.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Pr.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Aa extends Tr{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class ca extends Aa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ha extends Aa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("uniform vec4 color;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push(" float r = dot(cxy, cxy);"),o.push(" if (r > 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class ua extends Aa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class da extends Aa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class pa extends Aa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const fa=d.vec3(),ma=d.vec3(),ga=d.vec3(),_a=d.vec3(),va=d.mat4();class ba extends Tr{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=fa;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ma;if(l){const e=ga;d.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,va),m=_a,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform1f(this._uPointSize,1);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler"),this._uPointSize=e.getLocation("pointSize")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float pointSize;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ya=d.vec3(),wa=d.vec3(),Ba=d.vec3(),Pa=d.vec3(),xa=d.mat4();class Ca extends Tr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=ya;let f,m;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=wa;if(l){const e=Ba;d.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,xa),m=Pa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ma{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ca(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ha(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ua(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new da(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new pa(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ba(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ca(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ea={};class Fa{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ea[t];return i||(i=new Ma(e),Ea[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Ea[t],i._destroy()}))),i}(e.model.scene);const t=e.maxGeometryBatchSize||5e6,i=function(){const e=[];return{append:function(t,i=1,s=1){e.push({data:t,times:i,denormalizeScale:s})},compileBuffer:function(t){let i=0;e.forEach((e=>{i+=e.times*e.data.length}));const s=new t(i);let r=0;return e.forEach((e=>{const t=e.data,i=e.denormalizeScale,o=s.subarray(r);if(1===i)o.set(t,0);else for(let e=0;e<t.length;++e)o[e]=t[e]*i;let n=t.length;const a=e.times*t.length;for(;n<a;){const e=Math.min(n,a-n);o.set(o.subarray(0,e),n),n+=e}r+=n})),s}}};this._buffer={maxVerts:t,positions:i(),colors:i(),pickColors:i(),vertsIndex:0},this._scratchMemory=e.scratchMemory,this._state=new ae({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}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}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.vertsIndex+e/3<=this._buffer.maxVerts}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=this._buffer,s=this._preCompressedPositionsExpected?t.positionsCompressed:t.positions;if(!s)throw(this._preCompressedPositionsExpected?"positionsCompressed":"positions")+" expected";i.positions.append(s);const r=s.length/3,o=t.color,n=t.colorsCompressed,a=t.colors,l=t.pickColor;n?i.colors.append(n):a?i.colors.append(a,1,255):o&&i.colors.append([o[0],o[1],o[2],1],r),i.pickColors.append(l.slice(0,4),r),d.expandAABB3(this._modelAABB,t.aabb);const A=this._portions.length/2;return this._portions.push(this._buffer.vertsIndex),this._portions.push(r),this._buffer.vertsIndex+=r,this._numPortions++,this.model.numPortions++,this._meshes.push(e),A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer,s=(e,i,s)=>e.length>0?new le(t,t.ARRAY_BUFFER,e,e.length,i,s):null,r=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):go(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=s(r,3,t.STATIC_DRAW),e.flagsBuf=s(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=s(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=s(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?s(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=4)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=2*e,r=this._portions[s],o=this._portions[s+1],n=this._scratchMemory.getFloat32Array(o),a=!!(t&fr),l=!!(t&br),A=!!(t&yr),c=!!(t&wr),h=!!(t&gr),u=!!(t&mr);let d,p;d=!a||u||l||A&&!this.model.scene.highlightMaterial.glowThrough||c&&!this.model.scene.selectedMaterial.glowThrough?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,p=!a||u?Pr.NOT_RENDERED:c?Pr.SILHOUETTE_SELECTED:A?Pr.SILHOUETTE_HIGHLIGHTED:l?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let f=a&&!u&&h?Pr.PICK:Pr.NOT_RENDERED;const m=t&_r?1:0;for(let e=0;e<o;e++){let t=0;t|=d,t|=p<<4,t|=f<<12,t|=m<<16,n[e]=t}this._state.flagsBuf.setData(n,r)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Pr.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Pr.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Pr.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Pr.PICK)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class Ia extends Tr{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,i.positionsBuf.numItems,i.numInstances),r&&s.drawArrays++}}class Ta extends Ia{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Da extends Ia{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Sa extends Ia{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Ra extends Ia{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Ua extends Ia{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class La extends Ia{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("const float packUpScale = 256. / 255.;"),o.push("const float unpackDownscale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),o.push("const float shiftRight8 = 1.0 / 256.;"),o.push("vec4 packDepthToRGBA( const in float v ) {"),o.push(" vec4 r = vec4( fract( v * packFactors ), v );"),o.push(" r.yzw -= r.xyz * shiftRight8;"),o.push(" return r * packUpScale;"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push(" float r = dot(cxy, cxy);"),o.push(" if (r > 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class ka extends Ia{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Oa=d.vec3(),Na=d.vec3(),Va=d.vec3();d.vec3();const Qa=d.mat4();class Ha extends Tr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Oa;let f;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Na;if(l){const e=d.transformPoint3(c,l,Va);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,Qa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ja=d.vec3(),Ga=d.vec3(),za=d.vec3();d.vec3();const Wa=d.mat4();class Xa extends Tr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=t.aabb,u=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=ja;let f;if(p[0]=d.safeInv(h[3]-h[0])*d.MAX_INT,p[1]=d.safeInv(h[4]-h[1])*d.MAX_INT,p[2]=d.safeInv(h[5]-h[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(p[0]),e.snapPickCoordinateScale[1]=d.safeInv(p[1]),e.snapPickCoordinateScale[2]=d.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ga;if(l){const e=d.transformPoint3(c,l,za);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=Ye(u,t,Wa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=u,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ka{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ta(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Da(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new La(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Sa(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ra(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ua(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ka(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ha(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Xa(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Za={};const Ja=new Uint8Array(4),Ya=new Float32Array(1),qa=new Float32Array(3),$a=new Float32Array(4);class el{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Za[t];return i||(i=new Ka(e),Za[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Za[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new ae({obb:d.OBB3(),numInstances:0,origin:e.origin?d.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=e.geometry.primitive}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}createPortion(e,t){const i=t.meshMatrix,s=t.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),this._pickColors.push(s[0]),this._pickColors.push(s[1]),this._pickColors.push(s[2]),this._pickColors.push(s[3]),this._state.numInstances++;const r=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),r}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4,i=this._state,s=i.geometry;if(t>0){let s=!1;i.flagsBuf=new le(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new le(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=d.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new le(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new le(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new le(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Br&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Br?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ja[0]=t[0],Ja[1]=t[1],Ja[2]=t[2],this._state.colorsBuf.setData(Ja,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&fr),r=!!(t&br),o=!!(t&yr),n=!!(t&wr),a=!!(t&Br),l=!!(t&gr),A=!!(t&mr);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,h=!s||A?Pr.NOT_RENDERED:n?Pr.SILHOUETTE_SELECTED:o?Pr.SILHOUETTE_HIGHLIGHTED:r?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let u=0;u=!s||A?Pr.NOT_RENDERED:n?Pr.EDGES_SELECTED:o?Pr.EDGES_HIGHLIGHTED:r?Pr.EDGES_XRAYED:a?i?Pr.EDGES_COLOR_TRANSPARENT:Pr.EDGES_COLOR_OPAQUE:Pr.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?Pr.PICK:Pr.NOT_RENDERED)<<12,d|=(t&_r?255:0)<<16,Ya[0]=d,this._state.flagsBuf.setData(Ya,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(qa[0]=t[0],qa[1]=t[1],qa[2]=t[2],this._state.offsetsBuf.setData(qa,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;$a[0]=t[0],$a[1]=t[4],$a[2]=t[8],$a[3]=t[12],this._state.modelMatrixCol0Buf.setData($a,i),$a[0]=t[1],$a[1]=t[5],$a[2]=t[9],$a[3]=t[13],this._state.modelMatrixCol1Buf.setData($a,i),$a[0]=t[2],$a[1]=t[6],$a[2]=t[10],$a[3]=t[14],this._state.modelMatrixCol2Buf.setData($a,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Pr.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Pr.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Pr.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Pr.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const tl=d.vec3(),il=d.vec3(),sl=d.mat4();class rl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=o,u=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=tl;if(f){const t=d.transformPoint3(h,A,il);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=Ye(u,e,sl)}else p=u;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,tl,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uPerObjectDecodeMatrix="uPerObjectDecodeMatrix",this.uPerObjectColorAndFlags="uPerObjectColorAndFlags",this._uPerVertexPosition="uPerVertexPosition",this._uPerLineIndices="uPerLineIndices",this._uPerLineObject="uPerLineObject",this._uPerObjectMatrix="uPerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ol{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new rl(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const nl={};class al{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class ll{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class Al{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const cl={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(cl,null,4));let e=0;Object.keys(cl).forEach((t=>{t.startsWith("size")&&(e+=cl[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/cl.totalLines).toFixed(2)}`);let t={};Object.keys(cl).forEach((i=>{i.startsWith("size")&&(t[i]=`${(cl[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class hl{disableBindedTextureFiltering(e){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)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);cl.sizeDataColorsAndFlags+=l.byteLength,cl.numberOfTextures++;for(let e=0;e<o;e++)l.set(t[e],32*e+0),l.set(i[e],32*e+4),l.set([0,0,0,0],32*e+8),l.set([0,0,0,0],32*e+12),l.set([s[e]>>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),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),new Al(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);cl.sizeDataTextureOffsets+=r.byteLength,cl.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),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),new Al(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);cl.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),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),new Al(e,n,s,r,o)}generateTextureForPositionsDecodeMatrices(e,t){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);cl.sizeDataPositionDecodeMatrices+=o.byteLength,cl.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),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),new Al(e,n,s,r)}generateTextureFor8BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*3);cl.sizeDataTextureIndices+=o.byteLength,cl.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}generateTextureFor16BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*3);cl.sizeDataTextureIndices+=o.byteLength,cl.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}generateTextureFor32BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*3);cl.sizeDataTextureIndices+=o.byteLength,cl.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}generateTextureForPositions(e,t,i){const s=i/3,r=4096,o=Math.ceil(s/r);if(0===o)throw"texture height===0";const n=new Uint16Array(r*o*3);cl.sizeDataTexturePositions+=n.byteLength,cl.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];n.set(s,i),i+=s.length}const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,o),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,o,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,0),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),new Al(e,a,r,o)}generateTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const i=t.length,s=4096,r=Math.ceil(i/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r);o.set(t,0),cl.sizeDataTexturePortionIds+=o.byteLength,cl.numberOfTextures++;const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,o,0),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),new Al(e,n,s,r)}}const ul=new ho,dl=ul.maxDataTextureHeight,pl=new Float32Array(16),fl=new Uint8Array(4),ml=new Float32Array(3);let gl=0;const _l=d.identityMat4();class vl{constructor(e,t){cl.numberOfLayers++,this._layerNumber=gl++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._renderers=function(e){const t=e.id;let i=nl[t];return i||(i=new ol(e),nl[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete nl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new al,this._dataTextureState=new ll,this._dataTextureGenerator=new hl,this._state=new ae({origin:d.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}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}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&cl.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*dl||t+r>4096*dl)&&cl.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*dl&&t+r<=4096*dl}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;cl.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,cl.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||_l),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,cl.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,cl.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,cl.totalLines32Bits+=t.numLines),cl.totalLines+=t.numLines;for(let i=0;i<t.numLines;i+=8)e.push(A)}return this._subPortions.push({numVertices:t.numLines}),this._numPortions++,cl.numberOfPortions++,A}finalize(){if(this._finalized)return;const e=this._state,t=this._dataTextureState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dataTextureGenerator.generateTextureForInstancingMatrices(i,s.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(i,s.positionsCompressed,s.lenPositionsCompressed),t.texturePerLineIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId8Bits),t.texturePerLineIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId16Bits),t.texturePerLineIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId32Bits),s.lenIndices8Bits>0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetColor(i[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;fl[0]=t[0],fl[1]=t[1],fl[2]=t[2],fl[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(fl,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,fl))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e<o;e++)this._subPortionSetFlags(r[e],t,i,s)}_subPortionSetFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=!!(t&fr),o=!!(t&br),n=!!(t&mr);let a,l;a=!r||n||o?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,l=!r||n?Pr.NOT_RENDERED:!!(t&wr)?Pr.SILHOUETTE_SELECTED:!!(t&yr)?Pr.SILHOUETTE_HIGHLIGHTED:o?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let A=r&&!n&&!!(t&gr)?Pr.PICK:Pr.NOT_RENDERED;const c=this._dataTextureState,h=this.model.scene.canvas.gl;fl[0]=a,fl[1]=l,fl[3]=A,c.texturePerObjectColorsAndFlags._textureData.set(fl,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),h.bindTexture(h.TEXTURE_2D,c.texturePerObjectColorsAndFlags._texture),h.texSubImage2D(h.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,h.RGBA_INTEGER,h.UNSIGNED_BYTE,fl))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e<r;e++)this._subPortionSetFlags2(s[e],t,i)}_subPortionSetFlags2(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=t&_r?255:0,r=this._dataTextureState,o=this.model.scene.canvas.gl;fl[0]=s,fl[1]=0,fl[2]=1,fl[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(fl,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,fl))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetOffset(i[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;ml[0]=t[0],ml[1]=t[1],ml[2]=t[2],i.texturePerObjectOffsets._textureData.set(ml,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,ml))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetMatrix(i[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;pl.set(t),i.texturePerObjectInstanceMatrices._textureData.set(pl,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,pl))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const bl=d.vec3(),yl=d.vec3(),wl=d.vec3();d.vec3();const Bl=d.vec4(),Pl=d.mat4();class xl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=o;if(!this._program&&(this._allocate(),this.errors))return;let u,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=bl;if(f){const t=d.transformPoint3(h,A,yl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],u=Ye(r.viewMatrix,e,Pl),p=wl,p[0]=r.eye[0]-e[0],p[1]=r.eye[1]-e[1],p[2]=r.eye[2]-e[2]}else u=r.viewMatrix,p=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,u),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,p),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;s.crossSections&&(n.uniform4fv(this._uSliceColor,s.crossSections.sliceColor),n.uniform1f(this._uSliceThickness,s.crossSections.sliceThickness));for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,bl,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}this._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),e.crossSections&&(this._uSliceColor=s.getLocation("sliceColor"),this._uSliceThickness=s.getLocation("sliceThickness"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState.lights,o=t.camera.project;s.bind(),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=r.length;e<t;e++){const t=r[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const s=t.sao;if(s.possible){const t=i.drawingBufferWidth,r=i.drawingBufferHeight;Bl[0]=t,Bl[1]=r,Bl[2]=s.blendCutoff,Bl[3]=s.blendFactor,i.uniform4fv(this._uSAOParams,Bl),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++)r=i.lights[e],"ambient"!==r.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===r.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")));s&&(o.push("out vec4 vWorldPosition;"),o.push("flat out uint vFlags2;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int polygonIndex = gl_VertexID / 3;"),o.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e<t;e++)if(r=i.lights[e],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?o.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return o.push("vec3 rgb = vec3(color.rgb) / 255.0;"),o.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags2 = flags2.r;")),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(s.push(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Cl=new Float32Array([1,1,1]),Ml=d.vec3(),El=d.vec3(),Fl=d.vec3();d.vec3();const Il=d.mat4();class Tl{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=o,u=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const e=Ml;if(A){const t=El;d.transformPoint3(h,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=Ye(u,e,Il),f=Fl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=u,f=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Pr.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Pr.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Pr.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Cl);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),g=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*g,r=o.renderFlags;for(let t=0;t<m;t++){const s=this._uSectionPlanes[t];if(s)if(t<g){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,Ml,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("uniform vec4 color;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = color;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Dl=new Float32Array([0,0,0,1]),Sl=d.vec3(),Rl=d.vec3();d.vec3();const Ul=d.mat4();class Ll{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=Sl;if(f){const t=d.transformPoint3(h,A,Rl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=Ye(u,e,Ul)}else p=u;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Pr.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Pr.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Pr.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Dl);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,Sl,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const kl=d.vec3(),Ol=d.vec3(),Nl=d.mat4();class Vl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=kl;if(f){const t=d.transformPoint3(h,A,Ol);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=Ye(u,e,Nl)}else p=u;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,kl,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ql=d.vec3(),Hl=d.vec3(),jl=d.vec3(),Gl=d.mat4();class zl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=s,u=e.pickViewMatrix||o.viewMatrix,p=e.pickProjMatrix||o.projMatrix,f=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let g,_;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==c[0]||0!==c[1]||0!==c[2];if(v||b){const e=Ql;if(v){const t=d.transformPoint3(h,A,Hl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],g=Ye(u,e,Gl),_=jl,_[0]=f[0]-e[0],_[1]=f[1]-e[1],_[2]=f[2]-e[2]}else g=u,_=f;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),w=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*w,o=s.renderFlags;for(let t=0;t<y;t++){const r=this._uSectionPlanes[t];if(r)if(t<w){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,Ql,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("in vec4 vPickColor;"),i.push("out vec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Wl=d.vec3(),Xl=d.vec3(),Kl=d.vec3();d.vec3();const Zl=d.mat4();class Jl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=s,u=e.pickViewMatrix||o.viewMatrix,p=e.pickProjMatrix||o.projMatrix,f=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let g,_;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const t=Wl;if(A){const e=Xl;d.transformPoint3(h,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],g=Ye(u,t,Zl),_=Kl,_[0]=f[0]-t[0],_[1]=f[1]-t[1],_[2]=f[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=u,_=f,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const v=r._sectionPlanesState.getNumAllocatedSectionPlanes(),b=r._sectionPlanesState.sectionPlanes.length;if(v>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*b,o=s.renderFlags;for(let t=0;t<v;t++){const r=this._uSectionPlanes[t];if(r)if(t<b){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,Wl,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 packDepth(const in float depth) {"),i.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),i.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),i.push(" vec4 res = fract(depth * bitShift);"),i.push(" res -= res.xxyz * bitMask;"),i.push(" return res;"),i.push("}"),i.push("out vec4 outPackedDepth;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yl=d.vec3(),ql=d.vec3(),$l=d.vec3(),eA=d.vec3();d.vec3();const tA=d.mat4();class iA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix,f=Yl;let m,g;f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const _=0!==A[0]||0!==A[1]||0!==A[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(_||v){const t=ql;if(_){const e=d.transformPoint3(h,A,$l);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],m=Ye(p,t,tA),g=eA,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t<b;t++){const r=this._uSectionPlanes[t];if(r)if(t<y){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,Yl,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}const w="edge"===e.snapMode?n.LINES:n.POINTS;a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(w,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(w,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(w,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this.uVectorA=i.getLocation("uSnapVectorA"),this.uInverseVectorAB=i.getLocation("uSnapInvVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sA=d.vec3(),rA=d.vec3(),oA=d.vec3(),nA=d.vec3();d.vec3();const aA=d.mat4();class lA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix,f=sA;let m,g;f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const _=0!==A[0]||0!==A[1]||0!==A[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(_||v){const t=rA;if(_){const e=oA;d.transformPoint3(h,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],m=Ye(p,t,aA),g=nA,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t<b;t++){const r=this._uSectionPlanes[t];if(r)if(t<y){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,sA,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this._uVectorA=i.getLocation("uVectorAB"),this._uInverseVectorAB=i.getLocation("uInverseVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const AA=d.vec3(),cA=d.vec3(),hA=d.vec3();d.vec3();const uA=d.mat4();class dA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=s,u=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const e=AA;if(A){const t=cA;d.transformPoint3(h,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=Ye(u,e,uA),f=hA,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=u,f=o.eye;n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),g=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*g,o=s.renderFlags;for(let t=0;t<m;t++){const r=this._uSectionPlanes[t];if(r)if(t<g){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,AA,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(){const e=this._scene;e.canvas.gl,e.camera.project,this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push(" if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const pA=d.vec3(),fA=d.vec3(),mA=d.vec3();d.vec3();const gA=d.mat4();class _A{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=o;if(!this._program&&(this._allocate(),this.errors))return;let u,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=pA;if(f){const t=d.transformPoint3(h,A,fA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],u=Ye(r.viewMatrix,e,gA),p=mA,p[0]=r.eye[0]-e[0],p[1]=r.eye[1]-e[1],p[2]=r.eye[2]-e[2]}else u=r.viewMatrix,p=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,u),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,p),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,pA,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vA=d.vec3(),bA=d.vec3(),yA=d.vec3();d.vec3();const wA=d.mat4();class BA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,h=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let u,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const f=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(f||m){const e=vA;if(f){const t=bA;d.transformPoint3(c,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],u=Ye(h,e,wA),p=yA,p[0]=o.eye[0]-e[0],p[1]=o.eye[1]-e[1],p[2]=o.eye[2]-e[2]}else u=h,p=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,u),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(l){const e=tt(i.dist,i.dir,l,vA,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.objectDecodeAndInstanceMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2&&(this._aFlags2=i.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Mi.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Mi.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Mi.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Mi.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Mi.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t<e._sectionPlanesState.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in vec3 vViewNormal;"),i.push("vec3 packNormalToRGB( const in vec3 normal ) {"),i.push(" return normalize( normal ) * 0.5 + 0.5;"),i.push("}"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Mi.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const PA=d.vec3(),xA=d.vec3(),CA=d.vec3();d.vec3(),d.vec4();const MA=d.mat4();class EA{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:h}=o;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));const u=e.pickViewMatrix||r.viewMatrix,p=e.pickProjMatrix||r.projMatrix,f=e.pickOrigin||r.eye,m=e.pickProjMatrix?e.pickZFar:r.project.far;let g,_;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==c[0]||0!==c[1]||0!==c[2];if(v||b){const e=PA;if(v){const t=d.transformPoint3(h,A,xA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],g=Ye(u,e,MA),_=CA,_[0]=f[0]-e[0],_[1]=f[1]-e[1],_[2]=f[2]-e[2]}else g=u,_=f;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),w=s._sectionPlanesState.sectionPlanes.length;if(y>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*w,r=o.renderFlags;for(let t=0;t<y;t++){const s=this._uSectionPlanes[t];if(s)if(t<w){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=tt(i.dist,i.dir,A,PA,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ci(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out highp ivec4 outNormal;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class FA{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Tl(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new zl(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Jl(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new EA(this._scene)),this._snapRenderer||(this._snapRenderer=new iA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new lA(this._scene)),this._snapRenderer||(this._snapRenderer=new iA(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new xl(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new xl(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Tl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new _A(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new BA(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Ll(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Vl(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new zl(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new EA(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new EA(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Jl(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new iA(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new lA(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new dA(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const IA={};class TA{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class DA{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const SA={sizeDataColorsAndFlags: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(SA,null,4));let e=0;Object.keys(SA).forEach((t=>{t.startsWith("size")&&(e+=SA[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/SA.totalPolygons).toFixed(2)}`);let t={};Object.keys(SA).forEach((i=>{i.startsWith("size")&&(t[i]=`${(SA[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class RA{constructor(){}disableBindedTextureFiltering(e){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)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const c=new Uint8Array(16384*A);SA.sizeDataColorsAndFlags+=c.byteLength,SA.numberOfTextures++;for(let e=0;e<a;e++)c.set(t[e],32*e+0),c.set(i[e],32*e+4),c.set([0,0,0,0],32*e+8),c.set([0,0,0,0],32*e+12),c.set([s[e]>>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),c.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),c.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),c.set([n[e]?1:0,0,0,0],32*e+28);const h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),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),new Al(e,h,l,A,c)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);SA.sizeDataTextureOffsets+=r.byteLength,SA.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),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),new Al(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);SA.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),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),new Al(e,n,s,r,o)}createTextureForPositionsDecodeMatrices(e,t){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);SA.sizeDataPositionDecodeMatrices+=o.byteLength,SA.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),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),new Al(e,n,s,r)}createTextureFor8BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*3);SA.sizeDataTextureIndices+=o.byteLength,SA.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}createTextureFor16BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*3);SA.sizeDataTextureIndices+=o.byteLength,SA.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}createTextureFor32BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*3);SA.sizeDataTextureIndices+=o.byteLength,SA.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}createTextureFor8BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*2);SA.sizeDataTextureEdgeIndices+=o.byteLength,SA.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}createTextureFor16BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*2);SA.sizeDataTextureEdgeIndices+=o.byteLength,SA.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}createTextureFor32BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*2);SA.sizeDataTextureEdgeIndices+=o.byteLength,SA.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Al(e,n,s,r)}createTextureForPositions(e,t,i){const s=i/3,r=4096,o=Math.ceil(s/r);if(0===o)throw"texture height===0";const n=new Uint16Array(r*o*3);SA.sizeDataTexturePositions+=n.byteLength,SA.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];n.set(s,i),i+=s.length}const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,o),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,o,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,0),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),new Al(e,a,r,o)}createTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const i=t.length,s=4096,r=Math.ceil(i/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r);o.set(t,0),SA.sizeDataTexturePortionIds+=o.byteLength,SA.numberOfTextures++;const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,o,0),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),new Al(e,n,s,r)}}const UA=new ho,LA=UA.maxDataTextureHeight,kA=d.vec4(),OA=new Float32Array(16),NA=new Uint8Array(4),VA=new Float32Array(3);let QA=0;const HA=d.identityMat4();class jA{constructor(e,t){SA.numberOfLayers++,this._layerNumber=QA++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._renderers=function(e){const t=e.id;let i=IA[t];return i||(i=new FA(e),IA[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete IA[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new TA,this._dtxState=new DA,this._dtxTextureFactory=new RA,this._state=new ae({origin:d.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}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}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&SA.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*LA||t+r>4096*LA)&&SA.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*LA&&t+r<=4096*LA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;SA.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;SA.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,c=0;if(s){let e;c=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let h=0;if(r){let e;h=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,SA.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:c,numEdges:h,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,c=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||HA),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?c.numIndices8Bits:t.numVertices<=65536?c.numIndices16Bits:c.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?c.numEdgeIndices8Bits:t.numVertices<=65536?c.numEdgeIndices16Bits:c.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const h=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,c.numIndices8Bits+=i,SA.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,c.numIndices16Bits+=i,SA.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,c.numIndices32Bits+=i,SA.totalPolygons32Bits+=t.numTriangles),SA.totalPolygons+=t.numTriangles;for(let i=0;i<t.numTriangles;i+=8)e.push(h)}if(t.numEdges>0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,c.numEdgeIndices8Bits+=i,SA.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,c.numEdgeIndices16Bits+=i,SA.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,c.numEdgeIndices32Bits+=i,SA.totalEdges32Bits+=t.numEdges),SA.totalEdges+=t.numEdges;for(let i=0;i<t.numEdges;i+=8)e.push(h)}return this._subPortions.push({numVertices:t.numTriangles}),this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries[h]={indices:i.indices,positionsCompressed:i.positionsCompressed,positionsDecodeMatrix:e.positionsDecodeMatrix,meshMatrix:e.meshMatrix}),this._numPortions++,SA.numberOfPortions++,h}finalize(){if(this._finalized)return;const e=this._state,t=this._dtxState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectColorsAndFlags=this._dtxTextureFactory.createTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectEdgeIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dtxTextureFactory.createTextureForInstancingMatrices(i,s.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dtxTextureFactory.createTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dtxTextureFactory.createTextureForPositions(i,s.positionsCompressed,s.lenPositionsCompressed),t.texturePerPolygonIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId8Bits),t.texturePerPolygonIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId16Bits),t.texturePerPolygonIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId32Bits),s.perEdgeNumberPortionId8Bits.length>0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&fr&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&yr&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&br&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&wr&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&_r&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Br&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&gr&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&mr&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&fr?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&yr?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&br?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&wr?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Br?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&_r?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&mr?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&gr?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetColor(i[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;NA[0]=t[0],NA[1]=t[1],NA[2]=t[2],NA[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(NA,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,NA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e<o;e++)this._subPortionSetFlags(r[e],t,i,s)}_subPortionSetFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=!!(t&fr),o=!!(t&br),n=!!(t&yr),a=!!(t&wr),l=!!(t&Br),A=!!(t&gr),c=!!(t&mr);let h,u;h=!r||c||o||n&&!this.model.scene.highlightMaterial.glowThrough||a&&!this.model.scene.selectedMaterial.glowThrough?Pr.NOT_RENDERED:i?Pr.COLOR_TRANSPARENT:Pr.COLOR_OPAQUE,u=!r||c?Pr.NOT_RENDERED:a?Pr.SILHOUETTE_SELECTED:n?Pr.SILHOUETTE_HIGHLIGHTED:o?Pr.SILHOUETTE_XRAYED:Pr.NOT_RENDERED;let d=0;d=!r||c?Pr.NOT_RENDERED:a?Pr.EDGES_SELECTED:n?Pr.EDGES_HIGHLIGHTED:o?Pr.EDGES_XRAYED:l?i?Pr.EDGES_COLOR_TRANSPARENT:Pr.EDGES_COLOR_OPAQUE:Pr.NOT_RENDERED;let p=r&&!c&&A?Pr.PICK:Pr.NOT_RENDERED;const f=this._dtxState,m=this.model.scene.canvas.gl;NA[0]=h,NA[1]=u,NA[2]=d,NA[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(NA,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),m.bindTexture(m.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),m.texSubImage2D(m.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,m.RGBA_INTEGER,m.UNSIGNED_BYTE,NA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e<r;e++)this._subPortionSetFlags2(s[e],t,i)}_subPortionSetFlags2(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=t&_r?255:0,r=this._dtxState,o=this.model.scene.canvas.gl;NA[0]=s,NA[1]=0,NA[2]=1,NA[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(NA,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,NA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetOffset(i[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;VA[0]=t[0],VA[1]=t[1],VA[2]=t[2],i.texturePerObjectOffsets._textureData.set(VA,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,VA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetMatrix(i[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;OA.set(t),i.texturePerObjectInstanceMatrices._textureData.set(OA,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,OA))}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portionToSubPortionsMap[e];if(s)for(let e=0,r=s.length;e<r;e++){const r=s[e],o=this._subPortionReadableGeometries[r],n=o.positionsCompressed,a=o.positionsDecodeMatrix;o.meshMatrix;const l=i.origin,A=l[0],c=l[1],h=l[2],u=kA;for(let e=0,i=n.length;e<i;e+=3)u[0]=n[e],u[1]=n[e+1],u[2]=n[e+2],u[3]=1,d.decompressPosition(u,a),d.mulMat4v4(this.model.worldMatrix,u,u),u[0]+=A,u[1]+=c,u[2]+=h,t(u)}else this.model.error("portion not found: "+e)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._portionToSubPortionsMap[e];if(i)for(let e=0,s=i.length;e<s;e++){const s=i[e],r=this._subPortionReadableGeometries[s].indices;for(let e=0,i=r.length;e<i;e++)t(r[e])}else this.model.error("portion not found: "+e)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Pr.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Pr.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Pr.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Pr.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Pr.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Pr.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Pr.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Pr.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Pr.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Pr.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Pr.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,Pr.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class GA{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 zA{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const WA={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 XA{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 KA=new XA;class ZA{constructor(e){this.manager=void 0!==e?e:KA,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 JA={};class YA extends ZA{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=WA.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!==JA[e])return void JA[e].push({onLoad:t,onProgress:i,onError:s});JA[e]=[],JA[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).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=JA[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});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(l)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{WA.add(e,t);const i=JA[e];delete JA[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onLoad&&s.onLoad(t)}})).catch((t=>{const i=JA[e];if(void 0===i)throw this.manager.itemError(e),t;delete JA[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 qA{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 $A=0;class ec{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 qA,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 YA;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new YA;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=ec.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(ec.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(ec.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(ec.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}))})),$A>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),$A++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:c,dfdTransferFn:h,dfdFlags:u}=i;if("error"===A)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),$A--}}ec.BasisFormat={ETC1S:0,UASTC_4x4:1},ec.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},ec.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},ec.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.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:n,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),g=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,c){let h,u;const d=t===o.ETC1S?a:l;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||A(i)&&A(n))))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,f);if(!u||!d||!p)throw c(),new Error("KTX2TextureTranscoder: Invalid texture");if(!n.startTranscoding())throw c(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const b=[];for(let e=0;e<p;e++){const t=n.getImageLevelInfo(e,0,0),i=t.origWidth,s=t.origHeight,r=new Uint8Array(n.getImageTranscodedSizeInBytes(e,0,0,_));if(!n.transcodeImage(r,e,0,0,_,0,-1,-1))throw c(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");b.push({data:r,width:i,height:s})}return c(),{width:u,height:d,hasAlpha:f,mipmaps:b,format:v,dfdTransferFn:m,dfdFlags:g}}(c.buffers[0]),m=[];for(let e=0;e<u.length;++e)m.push(u[e].data.buffer);self.postMessage({type:"transcode",id:c.id,width:t,height:n,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f},m)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:c.id,error:e.message})}}))}var h}));const n=[{if:"astcSupported",basisFormat:[o.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:[o.ETC1S,o.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:[o.ETC1S,o.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:[o.ETC1S,o.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:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.ETC1],engineFormat:[s.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.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}],a=n.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),l=n.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function A(e){return e<=2||0==(e&e-1)&&0!==e}};const tc={};function ic(e){const t=e.scene.id;let i=tc[t];return i||(i=new ec({viewer:e}),tc[t]=i,e.scene.on("destroyed",(()=>{delete tc[t],i.destroy()}))),i}
|
|
@@ -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 ac=null;function lc(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const c=Math.min(r=ac[i],o=ac[i+1],n=ac[i+2]),h=Math.min(a=ac[s],l=ac[s+1],A=ac[s+2]);if(c!==h)return c-h;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let Ac=null;function cc(e,t){let i=Ac[2*e]-Ac[2*t];return 0!==i?i:Ac[2*e+1]-Ac[2*t+1]}function hc(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;ac=new Int32Array(e.length);for(let i=0,s=e.length;i<s;i++)ac[i]=e[i]>>t;i.sort(lc);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),o=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}Ac=new Int32Array(e),t.sort(cc);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 n(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=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<<t))return[e];const A=new Int32Array(l);A.fill(-1);const c=[];function h(){A.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 l=r[t],c=r[t+1],d=r[t+2];if(-1===A[l]&&i++,-1===A[c]&&i++,-1===A[d]&&i++,i+u.numPositions>u.maxNumPositions&&(u=h()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[c]&&(A[c]=u.numPositions++,u.positionsCompressed.push(s[3*c]),u.positionsCompressed.push(s[3*c+1]),u.positionsCompressed.push(s[3*c+2])),-1===A[d]&&(A[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(A[l]),u.indices.push(A[c]),u.indices.push(A[d]),(p=n(l,c))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(c,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let m=0,g=-s.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,g+=e.positionsCompressed.length/3})),m>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e<s;e+=3){const s=n[3*t[e]]+"_"+n[3*t[e]+1]+"_"+n[3*t[e]+2]+"/"+n[3*t[e+1]]+"_"+n[3*t[e+1]+1]+"_"+n[3*t[e+1]+2]+"/"+n[3*t[e+2]]+"_"+n[3*t[e+2]+1]+"_"+n[3*t[e+2]+2];i[s]=!0}r+=e.edgeIndices.length/2;for(let e=0,t=o.length;e<t;e+=2){const t=n[3*o[e]]+"_"+n[3*o[e]+1]+"_"+n[3*o[e]+2]+"/"+n[3*o[e+1]]+"_"+n[3*o[e+1]+1]+"_"+n[3*o[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 uc=new Float32Array([0,0,0]),dc=new Uint16Array([0,0,0]);d.OBB3();class pc{constructor(e,t,i,s,r,o){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=!!o,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(fr)}set visible(e){if(!!(this._flags&fr)!==e){this._flags=e?this._flags|fr:this._flags&~fr;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(yr)}set highlighted(e){if(!!(this._flags&yr)!==e){this._flags=e?this._flags|yr:this._flags&~yr;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(br)}set xrayed(e){if(!!(this._flags&br)!==e){this._flags=e?this._flags|br:this._flags&~br;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(wr)}set selected(e){if(!!(this._flags&wr)!==e){this._flags=e?this._flags|wr:this._flags&~wr;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(Br)}set edges(e){if(!!(this._flags&Br)!==e){this._flags=e?this._flags|Br:this._flags&~Br;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&mr)!==e){this._flags=e?this._flags|mr:this._flags&~mr;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(_r)}set clippable(e){if(!!(this._flags&_r)!==e){this._flags=e?this._flags|_r:this._flags&~_r;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(vr)}set collidable(e){if(!!(this._flags&vr)!==e){this._flags=e?this._flags|vr:this._flags&~vr;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(gr)}set pickable(e){if(!!(this._flags&gr)!==e){this._flags=e?this._flags|gr:this._flags&~gr;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 uc[0]=e[0]/255,uc[1]=e[1]/255,uc[2]=e[2]/255,uc}set colorize(e){if(e){dc[0]=Math.floor(255*e[0]),dc[1]=Math.floor(255*e[1]),dc[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(dc)}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 gs?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 fc=d.vec4(4),mc=d.vec4(),gc=d.vec4(),_c=d.vec3([1,0,0]),vc=d.vec3([0,1,0]),bc=d.vec3([0,0,1]);d.vec3(3),d.vec3(3);const yc=d.identityMat4();class wc{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||yc),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 fc[0]=e[0],fc[1]=e[1],fc[2]=e[2],fc[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(fc,mc),d.mulQuaternions(this.quaternion,mc,gc),this.quaternion=gc,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return fc[0]=e[0],fc[1]=e[1],fc[2]=e[2],fc[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(fc,mc),d.mulQuaternions(mc,this.quaternion,mc),this}rotateX(e){return this.rotate(_c,e)}rotateY(e){return this.rotate(vc,e)}rotateZ(e){return this.rotate(bc,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 Bc=d.vec3(),Pc=d.OBB3(),xc=d.vec4(),Cc=d.vec3([1,1,1]),Mc=d.vec3([0,0,0]);d.vec3([0,0,0]);const Ec=d.identityQuaternion(),Fc=d.identityMat4(),Ic=new Uint8Array([255,255,255]);class Tc extends R{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._vboBatchingLayerScratchMemory=(pr++,dr),this._textureTranscoder=t.textureTranscoder||ic(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=d.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},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 rs,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()})),this._createDefaultTextureSet(),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}_createDefaultTextureSet(){const e=new zA({id:"defaultColorTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new zA({id:"defaultMetalRoughTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new zA({id:"defaultNormalsTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new zA({id:"defaultEmissiveTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new zA({id:"defaultOcclusionTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new GA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}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||Fc),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:_o(e.aabb,d.mat4())}:this.error("[createQuantizationRange] Config missing: id")}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)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!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=_o(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=go(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),me.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&&me.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=Ae(e.positions,e.indices,null,5):e.edgeIndices=Ae(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){const t=me.getUVBounds(e.uv),i=me.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 o=e.wrapT||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);let n=e.wrapR||1e3;1001!==n&&1002!==n&&1e3!==n&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),n=1e3);let a=e.encoding||3e3;3e3!==a&&3001!==a&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),a=3e3);const l=new Ps({gl:this.scene.canvas.gl,minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,encoding:a});if(e.preloadColor&&l.setPreloadColor(e.preloadColor),e.image){const t=e.image;if(t.crossOrigin="Anonymous",t.compressed){const e=t.data;l.setCompressedData({mipmaps:e,props:{format:e[0].format,minFilter:i,magFilter:s}})}else l.setImage(t,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const A=new Image;A.onload=()=>{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).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,l).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 zA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new GA({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}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 wc({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;if(!(void 0!==e.geometryId)){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)return this.error(`Unsupported value for 'primitive': '${primitive}' ('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||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' 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;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Cc,i=e.position||Mc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",xc),e.meshMatrix=d.composeMat4(i,xc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||Ec,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=_o(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Ic,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];$e(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=go(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),me.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();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&&me.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}e.meshMatrix&&(d.AABB3ToOBB3(e.aabb,Pc),d.transformOBB3(e.meshMatrix,Pc),d.OBB3ToAABB3(Pc,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=Ae(e.positions,e.indices,null,2):e.edgeIndices=Ae(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=Dc(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];$e(e.positions,t,Bc)&&(e.positions=t,e.origin=d.addVec3(e.origin,Bc,d.vec3()))}if(e.positions){const t=d.collapseAABB3();e.meshMatrix&&(d.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),d.expandAABB3Points3(t,e.positions),e.aabb=t}else{const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),me.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.meshMatrix&&(d.AABB3ToOBB3(e.aabb,Pc),d.transformOBB3(e.meshMatrix,Pc),d.OBB3ToAABB3(Pc,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=Ae(e.positions,e.indices,null,2):e.edgeIndices=Ae(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`),!1}}else{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[e.geometryId],!e.geometry)return this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`),!1;if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return this.error(`[createMesh] Transform not found: ${e.transformId} - ensure that you create it first with createTransform()`),!1;e.aabb=e.geometry.aabb}else{if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Cc,i=e.position||Mc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",xc),e.meshMatrix=d.composeMat4(i,xc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||Ec,t,d.mat4())}d.AABB3ToOBB3(e.geometry.aabb,Pc),d.transformOBB3(e.meshMatrix,Pc),e.aabb=d.OBB3ToAABB3(Pc,d.AABB3())}if(!(!this._dtxEnabled||"triangles"!==e.geometry.primitive&&"solid"!==e.geometry.primitive&&"surface"!==e.geometry.primitive||e.textureSetId)){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Ic,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=Dc(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Ic,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId])}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createDefaultIndices(e){const t=[];for(let i=0;i<e;i++)t.push(i);return t}_createMesh(e){const t=new ur(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);const i=t.pickId,s=i>>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_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 jA(this,{layerIndex:0,origin:t,primitive:i});break;case"lines":r=new vl(this,{layerIndex:0,origin:t,primitive:i});break;default:return}return this._dtxLayers[s]=r,this.layerList.push(r),this._layersToFinalize.push(r),r}_getVBOBatchingLayer(e){const t=this,i=e.origin;e.renderLayer;const s=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",r=e.textureSetId||"-",o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${e.primitive}.${s}.${r}`;let n=this._vboBatchingLayers[o];if(n)return n;let a=e.textureSet;for(;!n;){switch(e.primitive){case"triangles":case"solid":case"surface":n=new To({model:t,textureSet:a,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0,primitive:e.primitive});break;case"lines":n=new Hn({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive});break;case"points":n=new Fa({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive})}const s=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?n.canCreatePortion(s):n.canCreatePortion(s,e.indices.length))||(n.finalize(),delete this._vboBatchingLayers[o],n=null)}return this._vboBatchingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}_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)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Bn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Bn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new la({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new el({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}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 void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=fr),this._pickable&&!1!==e.pickable&&(t|=gr),this._culled&&!1!==e.culled&&(t|=mr),this._clippable&&!1!==e.clippable&&(t|=_r),this._collidable&&!1!==e.collidable&&(t|=vr),this._edges&&!1!==e.edges&&(t|=Br),this._xrayed&&!1!==e.xrayed&&(t|=br),this._highlighted&&!1!==e.highlighted&&(t|=yr),this._selected&&!1!==e.selected&&(t|=wr),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;i<s;i++){const s=e.meshIds[i];let r=this._meshes[s];r?r.parent?this.error(`Mesh with ID "${s}" already belongs to object with ID "${r.parent.id}" - ignoring this mesh`):(t.push(r),delete this._unusedMeshes[s]):this.error(`Mesh with this ID not found: "${s}" - ignoring this mesh`)}const i=new pc(this,e.isObject,e.id,t,e.flags,!0);return this._entityList.push(i),this._entities[e.id]=i,this._entitiesToFinalize.push(i),this.numEntities++,i}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._vboBatchingLayers={},this._vboInstancingLayers={},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)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t<s;t++){const s=i.visibleLayers[t];this.layerList[s].drawColorOpaque(i,e)}}drawColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawColorTransparent(t,e)}}drawDepth(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawDepth(t,e)}}drawNormals(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawNormals(t,e)}}drawSilhouetteXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteXRayed(t,e)}}drawSilhouetteHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteHighlighted(t,e)}}drawSilhouetteSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteSelected(t,e)}}drawEdgesColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorOpaque(t,e)}}drawEdgesColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorTransparent(t,e)}}drawEdgesXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesXRayed(t,e)}}drawEdgesHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesHighlighted(t,e)}}drawEdgesSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesSelected(t,e)}}drawOcclusion(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawOcclusion(t,e)}}drawShadow(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawShadow(t,e)}}setPickMatrices(e,t){if(0===this._numVisibleLayerPortions)return;const i=this.renderFlags;for(let s=0,r=i.visibleLayers.length;s<r;s++){const r=i.visibleLayers[s],o=this.layerList[r];o.setPickMatrices&&o.setPickMatrices(e,t)}}drawPickMesh(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickMesh(t,e)}}drawPickDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickDepths(t,e)}}drawPickNormals(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickNormals(t,e)}}drawSnapInit(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnapInit&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnapInit(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}drawSnap(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnap&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnap(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}destroy(){for(let e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();this._vboBatchingLayers={};for(let e in this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(e)&&this._vboInstancingLayers[e].destroy();this._vboInstancingLayers={},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),0!==pr&&(pr--,0===pr&&dr._clear()),super.destroy()}}function Dc(e,t,i){let s,r,o,n;if(t||i?[s,r,o]=nc({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(s=e.positionsCompressed,r=e.indices,o=e.edgeIndices),i){n=hc({positionsCompressed:s,indices:r,edgeIndices:o},s.length/3>65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class Sc extends R{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 Tc(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 Rc extends R{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Uc extends Rc{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 Lc{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),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),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),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_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),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e<r.length;e++)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+e,s.TEXTURE_2D,r[e],0);if(e.length>0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))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={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,i||c.RGBA,s||c.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,c=new Uint8Array(4*n);for(let e=0;e<l;++e){const t=e*A,s=(a-e-1)*A;c.set(i.subarray(t,t+A)),i.copyWithin(t,s,s+A),i.set(c,s)}return r.data.set(i),o.putImageData(r,0,0),s}readImage(e){const t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,o=i.imageData,n=i.context,{width:a,height:l}=this.buffer;t.readPixels(0,0,a,l,t.RGBA,t.UNSIGNED_BYTE,s),o.data.set(s),n.putImageData(o,0,0),n.save(),n.globalCompositeOperation="copy",n.scale(1,-1),n.drawImage(r,0,-l,a,l),n.restore();let A=e.format||"png";return"jpeg"!==A&&"png"!==A&&"bmp"!==A&&(console.error("Unsupported image format: '"+A+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),A="png"),r.toDataURL(`image/${A}`)}_getImageDataCache(e=Uint8Array,t=4){const i=this.buffer.width,s=this.buffer.height;let r=this._imageDataCache;if(r&&(r.width===i&&r.height===s||(this._imageDataCache=null,r=null)),!r){const o=document.createElement("canvas"),n=o.getContext("2d");o.width=i,o.height=s,r={pixelData:new e(i*s*t),canvas:o,context:n,imageData:n.createImageData(i,s),width:i,height:s},this._imageDataCache=r}return r.context.resetTransform(),r}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(e=0){const t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}hasDepthTexture(){return this._hasDepthTexture}getDepthTexture(){if(!this._hasDepthTexture)return null;const e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}destroy(){if(this.allocated){const e=this.gl;this.buffer.textures.forEach((t=>e.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class kc extends Rc{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 ae({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 Lc(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[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 Oc extends Rc{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 ae({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 Lc(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[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 Nc(e){if(!Vc(e.width)||!Vc(e.height)){const t=document.createElement("canvas");t.width=Qc(e.width),t.height=Qc(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Vc(e){return 0==(e&e-1)}function Qc(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Hc extends R{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new ae({texture:new Ps({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),g.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}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o<e.length;o++){const n=new Image;n.onload=function(){let e=n;const a=o;return function(){if(!s&&(e=Nc(e),t._images[a]=e,r++,6===r)){let e=t._state.texture;e||(e=new Ps({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()}}}(),n.onerror=function(){s=!0},n.src=e[o]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),g.memory.textures--,this._state.destroy()}}class jc extends Hc{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 Gc extends Hc{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}}const zc=d.vec4(),Wc=d.vec4();class Xc extends R{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){zc.set(this._viewPos),zc[3]=1,d.transformPoint4(this.scene.camera.projMatrix,zc,Wc);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+Wc[0]/Wc[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-Wc[1]/Wc[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]),qe(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 Kc extends Xc{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 Is(this,{src:t.src}),this._geometry=new ve(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 fs(this,{geometry:this._geometry,material:new bs(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 Zc{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 Jc=d.vec3();class Yc{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?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!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),o&&(this.objectsXrayed[e]=t.xrayed),n&&(this.objectsHighlighted[e]=t.highlighted),a&&(this.objectsSelected[e]=t.selected),l&&(this.objectsClippable[e]=t.clippable),A&&(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,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!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]),o&&(t.xrayed=this.objectsXrayed[e]),n&&(t.highlighted=this.objectsHighlighted[e]),a&&(t.selected=this.objectsSelected[e]),l&&(t.clippable=this.objectsClippable[e]),A&&(t.pickable=this.objectsPickable[e]),c&&(Jc[0]=this.objectsColorize[3*e+0],Jc[1]=this.objectsColorize[3*e+1],Jc[2]=this.objectsColorize[3*e+2],t.colorize=Jc),h&&(t.opacity=this.objectsOpacity[e]))}}}const qc=d.vec3();class $c{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?y.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!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),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(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,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!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]),o&&(t.highlighted=this.objectsHighlighted[h]),n&&(t.selected=this.objectsSelected[h]),a&&(t.clippable=this.objectsClippable[h]),l&&(t.pickable=this.objectsPickable[h]),A&&(this.objectsHasColorize[h]?(qc[0]=this.objectsColorize[3*h+0],qc[1]=this.objectsColorize[3*h+1],qc[2]=this.objectsColorize[3*h+2],t.colorize=qc):t.colorize=null),c&&(t.opacity=this.objectsOpacity[h]),h++}}}class eh 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 th 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 o(){r._dirty=!0}function n(){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],y.isNumeric(t)||y.isString(t)){var a=t;if(!(t=this.scene.components[a])){this.error("Component not found: "+_inQuotes(a));continue}}var l=t.type;"xeokit.SplineCurve"===l||"xeokit.Path"===l||"xeokit.CubicBezierCurve"===l||"xeokit.QuadraticBezierCurve"===l?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",o)),this._destroyedSubs.push(t.once("destroyed",n))):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 o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}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 ih 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 sh extends Tc{constructor(e,t={}){super(e,t)}}const rh=d.vec3(),oh=d.vec3(),nh=d.vec4(),ah=d.vec3([0,0,-1]),lh=d.vec3([0,0,1]),Ah=d.vec3([0,1,0]);class ch extends R{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new ae({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,lh,this._state.dir);const t=d.vec3ApplyQuaternion(this._state.quaternion,Ah,rh),i=d.vec3PairToQuaternion(lh,this._state.dir,nh),s=d.vec3ApplyQuaternion(i,Ah,oh),r=Math.acos(Math.min(1,d.dotVec3(t,s))),o=Math.sign(d.dotVec3(this._state.dir,d.cross3Vec3(t,s,oh)));this._state.roll=o*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||ah),this._onDirRollUpdated()}_onDirRollUpdated(){d.vec3PairToQuaternion(lh,this._state.dir,this._state.quaternion),nh[0]=0,nh[1]=0,nh[2]=-1,nh[3]=this._state.roll,d.angleAxisToQuaternion(nh,nh),d.mulQuaternions(this._state.quaternion,nh,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 hh{transcode(e,t,i={}){}destroy(){}}class uh{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 dh={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 ph{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 o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}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 fh extends R{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 mh=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class gh extends R{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;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);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 fh(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<mh.length;e++)try{this.gl=this.canvas.getContext(mh[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,s){return this.scene._renderer.readPixels(e,t,i,s)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class _h{constructor(e){this._scene=e,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,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.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=d.vec3(),this.snapPickOrigin=d.vec3()}getRTCViewMatrix(e,t){let i=this._rtcViewMats[e];return i||(i=this._getNewMat(),Ye(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}getRTCPickViewMatrix(e,t){let i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();const s=this.pickViewMatrix||this._scene.camera.viewMatrix;Ye(s,t,i),this._rtcPickViewMats[e]=i}return i}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=d.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}class vh{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.vec3(t),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.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,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(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t<this.numMarkers;t++)if(this.markerList[t]){const i=this.markerList[t].rtcPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}_buildAABB(){const e=this.aabb;d.collapseAABB3(e),d.expandAABB3Points3(e,this.positions);const t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}_buildVBOs(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(new Float32Array(this.positions));this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,i=this.numMarkers;this.positionsBuf=new le(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new le(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,s=i[2],r=i[3];let o=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const i=this.markerList[e];if(i.viewPos[2]>-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i];if(t.active){const e=d.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const s=0===e;this.sectionPlanesActive[i]=s}else this.sectionPlanesActive[i]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const bh=d.vec3([1,0,0]),yh=d.vec3();class wh{constructor(e,t){this._scene=e,this._renderBufferManager=t,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=e.camera.on("viewMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new vh(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new vh(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildOcclusionLayersList(){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ci(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState,r=e.camera,o=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,i=this._occlusionLayersList.length;e<i;e++){const i=this._occlusionLayersList[e];if(i.update(),i.culledBySectionPlanes)continue;const o=i.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,Ye(r.viewMatrix,o));const n=s.sectionPlanes.length;if(n>0){const e=s.sectionPlanes;for(let s=0;s<n;s++){const r=this._uSectionPlanes[s];if(r){const n=i.sectionPlanesActive[s];if(t.uniform1i(r.active,n?1:0),n){const i=e[s];t.uniform3fv(r.pos,tt(i.dist,i.dir,o,yh)),t.uniform3fv(r.dir,i.dir)}}}}this._aPosition.bindArrayBuffer(i.positionsBuf);const a=i.indicesBuf;a.bind(),t.drawElements(t.POINTS,a.numItems,a.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*bh[0],i=255*bh[1],s=255*bh[2];for(let r=0,o=this._occlusionLayersList.length;r<o;r++){const o=this._occlusionLayersList[r];for(let r=0;r<o.lenOcclusionTestList;r++){const n=o.occlusionTestList[r],a=2*r,l=this._readPixelBuf.read(Math.round(o.pixels[a]*e),Math.round(o.pixels[a+1]*e)),A=l[0]===t&&l[1]===i&&l[2]===s;n._setVisible(A)}}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){if(!this.destroyed){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}const Bh=d.vec2();class Ph{constructor(e){this._scene=e,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){this._rebuild=!0}render(e){if(this._build(),this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,c=a.matrix,h=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;Bh[0]=o,Bh[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,h),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Bh),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e&&!this._rebuild)return;this._rebuild=!1;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ci(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new le(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new le(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new le(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const xh=new Float32Array(Th(17,[0,1])),Ch=new Float32Array(Th(17,[1,0])),Mh=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(Ih(s,t));return i}(17,4)),Eh=new Float32Array(2);class Fh{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Ci(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new le(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new le(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new le(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,c=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),Eh[0]=n,Eh[1]=a,s.uniform2fv(this._uViewport,Eh),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,c),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Ch):s.uniform2fv(this._uSampleOffsets,xh),s.uniform1fv(this._uSampleWeights,Mh);const h=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,h,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Ih(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Th(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class Dh{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new Lc(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}const Sh=d.vec3([0,0,0]),Rh=function(t,i){i=i||{};const s=new _h(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},c={},h=[],u=[],p=[],f=!0,m=!0,_=!0,v=!0,b=!0,y=!0,w=!0,B=!0;const P=new Dh(t);let x=!1;const C=new Ph(t),M=new Fh(t);function E(){f&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),f=!1,m=!0),m&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;t<s;t++){const s=i[t];h[e++]=s}}h.length=e,h.sort(((e,t)=>e.renderOrder-t.renderOrder))}(),m=!1,_=!0),_&&function(){let e=0,t=0;for(let i=0,s=h.length;i<s;i++){const s=h[i];s.rebuildRenderFlags(),s.renderFlags.culled||(s.isUI?p[t++]=s:u[e++]=s)}u.length=e,p.length=t}()}function F(e){if(!e.castsShadow)return;const t=e.getShadowRenderBuf();if(t){t.bind(),s.reset(),s.backfaces=!0,s.frontface=!0,s.shadowViewMatrix=e.getShadowViewMatrix(),s.shadowProjMatrix=e.getShadowProjMatrix(),o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,1),o.enable(o.DEPTH_TEST),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];!1!==i.visible&&i.castsShadow&&i.drawShadow&&(i.renderFlags.colorOpaque&&i.drawShadow(s))}}t.unbind()}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!ys(o,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!ys(o,"WEBGL_compressed_texture_etc"),dxtSupported:!!ys(o,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!ys(o,"EXT_texture_compression_bptc"),pvrtcSupported:!(!ys(o,"WEBGL_compressed_texture_pvrtc")&&!ys(o,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){v=e,_=!0},this.setEdgesEnabled=function(e){b=e,_=!0},this.setSAOEnabled=function(e){y=e,_=!0},this.setPBREnabled=function(e){w=e,_=!0},this.setColorTextureEnabled=function(e){B=e,_=!0},this.needStateSort=function(){m=!0},this.shadowsDirty=function(){},this.imageDirty=function(){_=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){C.init(),M.init(),_=!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=A[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},A[i]=s),s.count++,s.drawableMap[e]=t,c[e]=t,f=!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=A[i];--s.count<=0?delete A[i]:delete s.drawableMap[e],delete c[e],f=!0},this.getPickID=function(e){return l.addItem(e)},this.putPickID=function(e){l.removeItem(e)},this.clear=function(e){if(o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT)},this.needsRender=function(){return _||f||m},this.render=function(e){(e=e||{}).force&&(_=!0),E(),_&&(!function(e){const i=t.sao;y&&i.possible&&function(e){const i=t.sao,r=P.getRenderBuffer("saoDepth",{depthTexture:!0});r.bind(),r.clear(),function(e){s.reset(),s.pass=e.pass,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=u.length;e<t;e++){const t=u[e];!0!==t.culled&&!1!==t.visible&&t.drawDepth&&t.saoEnabled&&(t.renderFlags.colorOpaque&&t.drawDepth(s))}}(e),r.unbind();const n=P.getRenderBuffer("saoOcclusion");if(n.bind(),n.clear(),C.render(r),n.unbind(),i.blur){const e=P.getRenderBuffer("saoOcclusion2");e.bind(),e.clear(),M.render(r,n,0),e.unbind(),n.bind(),n.clear(),M.render(r,e,1),n.unbind()}}(e);(function(){let e=t._lightsState.lights;for(let t=0,i=e.length;t<i;t++){const i=e[t];i.castsShadow&&F(i)}})(),function(e){const i=[],r=[],l=[],A=[],c=[],h=[],f=[],m=[],_=[],x=[],C=[],M=[],E=[],F=[],I=[],T=[],D=t._lightsState.getAmbientColorAndIntensity();if(s.reset(),s.pass=e.pass,s.withSAO=!1,s.pbrEnabled=w&&!!t.pbrEnabled,s.colorTextureEnabled=B&&!!t.colorTextureEnabled,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?D:t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),o.lineWidth(1),s.lineWidth=1;const S=t.sao.possible;if(y&&S){const e=P.getRenderBuffer("saoOcclusion");s.occlusionTexture=e?e.getTexture():null}else s.occlusionTexture=null;let R,U;const L=Date.now();!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const k=function(e){let u=0,p=0,g=0,w=0,B=0,P=0,D=0,L=0,k=0,O=0,N=0,V=0,Q=0,H=0,j=0,G=0;for(let t=0,o=e.length;t<o;t++){if(U=e[t],!0===U.culled||!1===U.visible)continue;const o=U.renderFlags;o.colorOpaque&&(y&&S&&U.saoEnabled?i[u++]=U:U.drawColorOpaque(s)),v&&o.colorTransparent&&(l[g++]=U),o.xrayedSilhouetteTransparent&&(f[D++]=U),o.xrayedSilhouetteOpaque&&(c[B++]=U),o.highlightedSilhouetteTransparent&&(C[N++]=U),o.highlightedSilhouetteOpaque&&(_[k++]=U),o.selectedSilhouetteTransparent&&(I[j++]=U),o.selectedSilhouetteOpaque&&(E[Q++]=U),U.edges&&b&&(o.edgesOpaque&&(r[p++]=U),o.edgesTransparent&&(A[w++]=U),o.selectedEdgesTransparent&&(T[G++]=U),o.selectedEdgesOpaque&&(F[H++]=U),o.xrayedEdgesTransparent&&(m[L++]=U),o.xrayedEdgesOpaque&&(h[P++]=U),o.highlightedEdgesTransparent&&(M[V++]=U),o.highlightedEdgesOpaque&&(x[O++]=U))}if(u>0)for(s.withSAO=!0,R=0;R<u;R++)i[R].drawColorOpaque(s);if(p>0)for(R=0;R<p;R++)r[R].drawEdgesColorOpaque(s);if(B>0)for(R=0;R<B;R++)c[R].drawSilhouetteXRayed(s);if(P>0)for(R=0;R<P;R++)h[R].drawEdgesXRayed(s);if(D>0||L>0||g>0||w>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(g>0||w>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),w>0)for(R=0;R<w;R++)U=A[R],U.drawEdgesColorTransparent(s);if(g>0){const e=s.pickOrigin||t.camera.eye,i=l.map((t=>({drawable:t,distSq:d.distVec3(t.origin||Sh,e)})));for(i.sort(((e,t)=>t.distSq-e.distSq)),R=0;R<g;R++)i[R].drawable.drawColorTransparent(s)}if(L>0)for(R=0;R<L;R++)m[R].drawEdgesXRayed(s);if(D>0)for(R=0;R<D;R++)f[R].drawSilhouetteXRayed(s);o.disable(o.BLEND),a||o.depthMask(!0)}if(k>0||O>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),O>0)for(R=0;R<O;R++)x[R].drawEdgesHighlighted(s);if(k>0)for(R=0;R<k;R++)_[R].drawSilhouetteHighlighted(s)}if(N>0||V>0||k>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),V>0)for(R=0;R<V;R++)M[R].drawEdgesHighlighted(s);if(N>0)for(R=0;R<N;R++)C[R].drawSilhouetteHighlighted(s);o.disable(o.BLEND)}if(Q>0||H>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),H>0)for(R=0;R<H;R++)F[R].drawEdgesSelected(s);if(Q>0)for(R=0;R<Q;R++)E[R].drawSilhouetteSelected(s)}if(j>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),G>0)for(R=0;R<G;R++)T[R].drawEdgesSelected(s);if(j>0)for(R=0;R<j;R++)I[R].drawSilhouetteSelected(s);o.disable(o.BLEND)}};k(u),p.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),k(p));const O=Date.now(),N=g.frame;N.renderTime=(O-L)/1e3,N.drawElements=s.drawElements,N.drawArrays=s.drawArrays,N.useProgram=s.useProgram,N.bindTexture=s.bindTexture,N.bindArray=s.bindArray;const V=Mi.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<V;e++)o.activeTexture(o.TEXTURE0+e);o.bindTexture(o.TEXTURE_CUBE_MAP,null),o.bindTexture(o.TEXTURE_2D,null);const Q=Mi.MAX_VERTEX_ATTRIBS;for(let e=0;e<Q;e++)o.disableVertexAttribArray(e)}(e)}(e),g.frame.frameCount++,_=!1)},this.pick=function(){const e=d.vec3();d.mat4();const i=d.mat4(),n=d.vec3(),a=d.vec3([0,1,0]),c=new uh,h=d.vec2(),f=d.vec3(),m=d.vec3(),g=d.vec3();return d.vec3(),d.vec3(),function(_,v=c){let b;v.reset(),E();let y=null,w=null,B=null;v.pickSurface=_.pickSurface,_.canvasPos?(f[0]=_.canvasPos[0],f[1]=_.canvasPos[1],y=t.camera.viewMatrix,w=t.camera.projMatrix,B=t.camera.projection,h[0]=t.camera.project.near,h[1]=t.camera.project.far,v.canvasPos=_.canvasPos):(_.matrix?(y=_.matrix,w=t.camera.projMatrix,B=t.camera.projection,h[0]=t.camera.project.near,h[1]=t.camera.project.far):(m.set(_.origin||[0,0,0]),g.set(_.direction||[0,0,1]),b=d.addVec3(m,g,e),n[0]=Math.random(),n[1]=Math.random(),n[2]=Math.random(),d.normalizeVec3(n),d.cross3Vec3(g,n,a),y=d.lookAtMat4v(m,b,a,i),w=t.camera.ortho.matrix,B="ortho",h[0]=t.camera.ortho.near,h[1]=t.camera.ortho.far,v.origin=m,v.direction=g),f[0]=.5*r.clientWidth,f[1]=.5*r.clientHeight);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(y,w)}}const x=P.getRenderBuffer("pick",{size:[1,1]});x.bind();const C=function(e,i,r,n,a,A){const c=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=A.origin,s.pickViewMatrix=r,s.pickProjMatrix=n,s.pickInvisible=!!a.pickInvisible,s.pickClipPos=[D(i[0]*c,o.drawingBufferWidth),S(i[1]*c,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const h=a.includeEntityIds,d=a.excludeEntityIds,f=function(e){for(let t=0,i=e.length;t<i;t++){const i=e[t];!0!==i.culled&&!1!==i.visible&&(!i.drawPickMesh||!0!==a.pickInvisible&&!1===i.visible||!1===i.pickable||h&&!h[i.id]||d&&d[i.id]||i.drawPickMesh(s))}};f(u),p.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),f(p));const m=e.read(0,0),g=m[0]+(m[1]<<8)+(m[2]<<16)+(m[3]<<24);if(g<0)return;return l.items[g]}(x,f,y,w,_,v);if(!C)return x.unbind(),null;const M=C.delegatePickedEntity?C.delegatePickedEntity():C;return M?(_.pickSurface&&(C.canPickTriangle&&C.canPickTriangle()?(!function(e,i,r,n,a,l){if(!i.drawPickTriangles)return;const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),i.drawPickTriangles(s);const c=e.read(0,0);let h=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;h*=3,l.primIndex=h}(x,C,f,y,w,v),C.pickTriangleSurface(y,w,B,v),v.pickSurfacePrecision=!1):C.canPickWorldPos&&C.canPickWorldPos()&&(I(x,C,f,y,w,h,v),!1!==_.pickSurfaceNormal&&function(e,i,r,n,a,l){const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)];const c=P.getRenderBuffer("pick-normal",{size:[3,3]});c.bind(o.RGBA32I),o.viewport(0,0,c.size[0],c.size[1]),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),i.drawPickNormals(s);const h=c.read(1,1,o.RGBA_INTEGER,o.INT,Int32Array,4);c.unbind();const u=[h[0]/d.MAX_INT,h[1]/d.MAX_INT,h[2]/d.MAX_INT];d.normalizeVec3(u),l.worldNormal=u}(0,C,f,y,w,v),v.pickSurfacePrecision=!1)),x.unbind(),v.entity=M,v):(x.unbind(),null)}}();const I=function(){const e=d.vec4(),i=d.vec4(),n=d.vec4(),a=d.vec4(),l=d.vec4(),A=d.mat4(),c=d.mat4(),h=d.mat4();return function(u,p,f,m,g,_,v){const b=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=v.origin,s.pickViewMatrix=m,s.pickProjMatrix=g,s.pickZNear=_[0],s.pickZFar=_[1],s.pickElementsCount=p.pickElementsCount,s.pickElementsOffset=p.pickElementsOffset,s.pickClipPos=[D(f[0]*b,o.drawingBufferWidth),S(f[1]*b,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),p.drawPickDepths(s);const y=function(e){const t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],i=[1/16777216,1/65536,1/256,1];return d.dotVec4(t,i)}(u.read(0,0)),w=(f[0]-r.clientWidth/2)/(r.clientWidth/2),B=-(f[1]-r.clientHeight/2)/(r.clientHeight/2),P=p.origin;let x;if(P){const e=Ye(m,P,A);x=d.mulMat4(g,e,c)}else x=d.mulMat4(g,m,c);const C=d.inverseMat4(x,h);e[0]=w,e[1]=B,e[2]=-1,e[3]=1;let M=d.transformVec4(C,e);M=d.mulVec4Scalar(M,1/M[3]),i[0]=w,i[1]=B,i[2]=1,i[3]=1;let E=d.transformVec4(C,i);E=d.mulVec4Scalar(E,1/E[3]);const F=d.subVec3(E,M,n),I=d.addVec3(M,d.mulVec4Scalar(F,y,a),l);P&&d.addVec3(I,P),v.worldPos=I}}();function T(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(let t=0,i=u.length;t<i;t++){const i=u[t];i.drawSnapInit&&i.drawSnap&&!i.culled&&i.visible&&i.pickable&&i.drawSnap(e)}return e.snapPickLayerParams}function D(e,t){return e/t*2-1}function S(e,t){return 1-e/t*2}this.snapPick=function(){const e=new uh;return function(i,r=e){const{canvasPos:n,origin:a,direction:c,snapRadius:h,snapToVertex:p,snapToEdge:f}=i;if(!p&&!f)return this.pick({canvasPos:n,pickSurface:!0});const m=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickZNear=t.camera.project.near,s.pickZFar=t.camera.project.far;const g=h||30,_=P.getRenderBuffer(`uniquePickColors-aabs-${g}`,{depthTexture:!0,size:[2*g+1,2*g+1]});s.snapVectorA=[n?D(n[0]*m,o.drawingBufferWidth):0,n?S(n[1]*m,o.drawingBufferHeight):0],s.snapInvVectorAB=[o.drawingBufferWidth/(2*g),o.drawingBufferHeight/(2*g)],_.bind(o.RGBA32I,o.RGBA32I,o.RGBA8UI),o.viewport(0,0,_.size[0],_.size[1]),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.disable(o.CULL_FACE),o.depthMask(!0),o.disable(o.BLEND),o.depthFunc(o.LEQUAL),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),o.clearBufferiv(o.COLOR,1,new Int32Array([0,0,0,0])),o.clearBufferuiv(o.COLOR,2,new Uint32Array([0,0,0,0])),s.pickViewMatrix=n?t.camera.viewMatrix:d.lookAtMat4v(a,d.addVec3(a,c,d.vec3()),d.vec3([0,1,0]),d.mat4());const v=t.camera.projMatrix;for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(s.pickViewMatrix,v)}}o.drawBuffers([o.COLOR_ATTACHMENT0,o.COLOR_ATTACHMENT1,o.COLOR_ATTACHMENT2]);const b=function(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(let t=0,i=u.length;t<i;t++){const i=u[t];i.drawSnapInit&&!i.culled&&i.visible&&i.pickable&&i.drawSnapInit(e)}return e.snapPickLayerParams}(s),y=[];s.snapPickLayerParams=y,o.depthMask(!1),o.drawBuffers([o.COLOR_ATTACHMENT0]),p&&f?(s.snapMode="edge",T(s),s.snapMode="vertex",s.snapPickLayerNumber++,T(s)):(s.snapMode=p?"vertex":"edge",T(s)),o.depthMask(!0);const w=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4),B=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4,1),x=_.readArray(o.RGBA_INTEGER,o.UNSIGNED_INT,Uint32Array,4,2);_.unbind();let C=null,M=null,E=null;const F=4*g+g*_.size[0]*4,I=w.slice(F,F+4),R=B.slice(F,F+4),U=x.slice(F,F+4);if(0!==I[3]){const e=b[Math.abs(I[3])%b.length],t=e.origin,i=e.coordinateScale;C=[I[0]*i[0]+t[0],I[1]*i[1]+t[1],I[2]*i[2]+t[2]],M=d.normalizeVec3([R[0]/d.MAX_INT,R[1]/d.MAX_INT,R[2]/d.MAX_INT]);const s=U[0]+(U[1]<<8)+(U[2]<<16)+(U[3]<<24);E=l.items[s]}let L=[];for(let e=0;e<w.length;e+=4)if(w[e+3]>0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));L.push({x:s,y:r,dist:o,isVertex:p&&f?w[e+3]>y.length/2:p,result:[w[e+0],w[e+1],w[e+2],w[e+3]],normal:[B[e+0],B[e+1],B[e+2],B[e+3]],id:[x[e+0],x[e+1],x[e+2],x[e+3]]})}let k=null,O=null,N=null,V=null;if(L.length>0){L.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),V=L[0].isVertex?"vertex":"edge";const e=L[0].result,t=L[0].normal,i=L[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;O=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),k=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==k)return null;let Q=null;null!==k&&(Q=t.camera.projectWorldPos(k));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&E&&(E=E.delegatePickedEntity?E.delegatePickedEntity():E),r.reset(),r.snappedToEdge="edge"===V,r.snappedToVertex="vertex"===V,r.worldPos=k||C,r.worldNormal=O||M,r.entity=H||E,r.canvasPos=n||t.camera.projectWorldPos(C||k),r.snappedCanvasPos=Q||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new wh(t,P),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){E(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=u.length;e<t;e++){const t=u[e];t.drawOcclusion&&!0!==t.culled&&!1!==t.visible&&!1!==t.pickable&&t.drawOcclusion(s)}this._occlusionTester.drawMarkers(s),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,s){const r=P.getRenderBuffer("snapshot");let o,n,a,l;for(r.bind(),r.clear(),this.render({force:!0,opaqueOnly:s}),n=0;n<i;n++)a=2*n,l=4*n,o=r.read(e[a],e[a+1]),t[l]=o[0],t[l+1]=o[1],t[l+2]=o[2],t[l+3]=o[3];r.unbind(),_=!0},this.beginSnapshot=function(e={}){const t=P.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),x=!0},this.renderSnapshot=function(){if(!x)return;P.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),_=!0},this.readSnapshot=function(e){return P.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return P.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){if(!x)return;P.getRenderBuffer("snapshot").unbind(),x=!1},this.destroy=function(){A={},c={},P.destroy(),C.destroy(),M.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class Uh extends R{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 Lh extends R{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new ae({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 kh extends R{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Oh extends R{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Nh extends R{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Vh extends R{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Qh=d.vec3(),Hh=d.vec3(),jh=d.vec3(),Gh=d.vec3(),zh=d.vec3(),Wh=d.vec3(),Xh=d.vec4(),Kh=d.vec4(),Zh=d.vec4(),Jh=d.mat4(),Yh=d.mat4(),qh=d.vec3(),$h=d.vec3(),eu=d.vec3(),tu=d.vec3();class iu extends R{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new ae({offsetEyeFromLook:!0,deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new kh(this),this._ortho=new Oh(this),this._frustum=new Nh(this),this._customProjection=new Vh(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,qh),d.normalizeVec3(qh,$h),d.mulVec3Scalar($h,1e3,eu),d.addVec3(this._look,eu,tu),t=tu):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Yh),d.mulMat4(e.deviceMatrix,Yh,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,Qh);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Jh),t=d.transformPoint3(Jh,t,Hh),this.eye=d.addVec3(this._look,t,jh),this.up=d.transformPoint3(Jh,this._up,Gh)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,Qh);const i=d.cross3Vec3(d.normalizeVec3(t,Hh),d.normalizeVec3(this._up,jh));d.rotationMat4v(.0174532925*e,i,Jh),t=d.transformPoint3(Jh,t,Gh),this.up=d.transformPoint3(Jh,this._up,zh),this.eye=d.addVec3(t,this._look,Wh)}yaw(e){let t=d.subVec3(this._look,this._eye,Qh);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Jh),t=d.transformPoint3(Jh,t,Hh),this.look=d.addVec3(t,this._eye,jh),this._gimbalLock&&(this.up=d.transformPoint3(Jh,this._up,Gh))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,Qh);const i=d.cross3Vec3(d.normalizeVec3(t,Hh),d.normalizeVec3(this._up,jh));d.rotationMat4v(.0174532925*e,i,Jh),this.up=d.transformPoint3(Jh,this._up,Wh),t=d.transformPoint3(Jh,t,Gh),this.look=d.addVec3(t,this._eye,zh)}pan(e){const t=d.subVec3(this._eye,this._look,Qh),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,Hh));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,jh),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,Gh),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,zh),this.look=d.addVec3(this._look,i,Wh)}zoom(e){const t=d.subVec3(this._eye,this._look,Qh),i=Math.abs(d.lenVec3(t,Hh)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,jh);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),Gh)}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,Qh))}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=Xh,i=Kh,s=Zh;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,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}const su={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 ru extends R{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 su}set units(e){e||(e="meters");su[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 ou extends R{constructor(e,t={}){super(e,t),this._supported=Mi.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 nu extends R{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 au={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class lu extends gs{get type(){return"PointsMaterial"}get presets(){return au}constructor(e,t={}){super(e,t),this._state=new ae({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=au[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(au).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 Au={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class cu extends gs{get type(){return"LinesMaterial"}get presets(){return Au}constructor(e,t={}){super(e,t),this._state=new ae({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=Au[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Au).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function hu(e,t,i=2){const s=t&&t.length,r=s?t[0]*i:e.length;let o=uu(e,0,r,i,!0);const n=[];if(!o||o.next===o.prev)return n;let a,l,A;if(s&&(o=function(e,t,i,s){const r=[];for(let i=0,o=t.length;i<o;i++){const n=uu(e,t[i]*s,i<o-1?t[i+1]*s:e.length,s,!1);n===n.next&&(n.steiner=!0),r.push(Bu(n))}r.sort(vu);for(let e=0;e<r.length;e++)i=bu(r[e],i);return i}(e,t,o,i)),e.length>80*i){a=1/0,l=1/0;let t=-1/0,s=-1/0;for(let o=i;o<r;o+=i){const i=e[o],r=e[o+1];i<a&&(a=i),r<l&&(l=r),i>t&&(t=i),r>s&&(s=r)}A=Math.max(t-a,s-l),A=0!==A?32767/A:0}return pu(o,n,i,a,l,A,0),n}function uu(e,t,i,s,r){let o;if(r===function(e,t,i,s){let r=0;for(let o=t,n=i-s;o<i;o+=s)r+=(e[n]-e[o])*(e[o+1]+e[n+1]),n=o;return r}(e,t,i,s)>0)for(let r=t;r<i;r+=s)o=Ru(r/s|0,e[r],e[r+1],o);else for(let r=i-s;r>=t;r-=s)o=Ru(r/s|0,e[r],e[r+1],o);return o&&Eu(o,o.next)&&(Uu(o),o=o.next),o}function du(e,t){if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!Eu(s,s.next)&&0!==Mu(s.prev,s,s.next))s=s.next;else{if(Uu(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t}function pu(e,t,i,s,r,o,n){if(!e)return;!n&&o&&function(e,t,i,s){let r=e;do{0===r.z&&(r.z=wu(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 o=null;for(t=0;r;){t++;let n=r,a=0;for(let e=0;e<i&&(a++,n=n.nextZ,n);e++);let l=i;for(;a>0||l>0&&n;)0!==a&&(0===l||!n||r.z<=n.z)?(s=r,r=r.nextZ,a--):(s=n,n=n.nextZ,l--),o?o.nextZ=s:e=s,s.prevZ=o,o=s;r=n}o.nextZ=null,i*=2}while(t>1)}(r)}(e,s,r,o);let a=e;for(;e.prev!==e.next;){const l=e.prev,A=e.next;if(o?mu(e,s,r,o):fu(e))t.push(l.i,e.i,A.i),Uu(e),e=A.next,a=A.next;else if((e=A)===a){n?1===n?pu(e=gu(du(e),t),t,i,s,r,o,2):2===n&&_u(e,t,i,s,r,o):pu(du(e),t,i,s,r,o,1);break}}}function fu(e){const t=e.prev,i=e,s=e.next;if(Mu(t,i,s)>=0)return!1;const r=t.x,o=i.x,n=s.x,a=t.y,l=i.y,A=s.y,c=Math.min(r,o,n),h=Math.min(a,l,A),u=Math.max(r,o,n),d=Math.max(a,l,A);let p=s.next;for(;p!==t;){if(p.x>=c&&p.x<=u&&p.y>=h&&p.y<=d&&xu(r,a,o,l,n,A,p.x,p.y)&&Mu(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function mu(e,t,i,s){const r=e.prev,o=e,n=e.next;if(Mu(r,o,n)>=0)return!1;const a=r.x,l=o.x,A=n.x,c=r.y,h=o.y,u=n.y,d=Math.min(a,l,A),p=Math.min(c,h,u),f=Math.max(a,l,A),m=Math.max(c,h,u),g=wu(d,p,t,i,s),_=wu(f,m,t,i,s);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=g&&b&&b.z<=_;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&xu(a,c,l,h,A,u,v.x,v.y)&&Mu(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&xu(a,c,l,h,A,u,b.x,b.y)&&Mu(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=g;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&xu(a,c,l,h,A,u,v.x,v.y)&&Mu(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=_;){if(b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&xu(a,c,l,h,A,u,b.x,b.y)&&Mu(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function gu(e,t){let i=e;do{const s=i.prev,r=i.next.next;!Eu(s,r)&&Fu(s,i,i.next,r)&&Du(s,r)&&Du(r,s)&&(t.push(s.i,i.i,r.i),Uu(i),Uu(i.next),i=e=r),i=i.next}while(i!==e);return du(i)}function _u(e,t,i,s,r,o){let n=e;do{let e=n.next.next;for(;e!==n.prev;){if(n.i!==e.i&&Cu(n,e)){let a=Su(n,e);return n=du(n,n.next),a=du(a,a.next),pu(n,t,i,s,r,o,0),void pu(a,t,i,s,r,o,0)}e=e.next}n=n.next}while(n!==e)}function vu(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 bu(e,t){const i=function(e,t){let i=t;const s=e.x,r=e.y;let o,n=-1/0;if(Eu(e,i))return i;do{if(Eu(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>n&&(n=e,o=i.x<i.next.x?i:i.next,e===s))return o}i=i.next}while(i!==t);if(!o)return null;const a=o,l=o.x,A=o.y;let c=1/0;i=o;do{if(s>=i.x&&i.x>=l&&s!==i.x&&Pu(r<A?s:n,r,l,A,r<A?n:s,r,i.x,i.y)){const t=Math.abs(r-i.y)/(s-i.x);Du(i,e)&&(t<c||t===c&&(i.x>o.x||i.x===o.x&&yu(o,i)))&&(o=i,c=t)}i=i.next}while(i!==a);return o}(e,t);if(!i)return t;const s=Su(i,e);return du(s,s.next),du(i,i.next)}function yu(e,t){return Mu(e.prev,e,t.prev)<0&&Mu(t.next,e,e.next)<0}function wu(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 Bu(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 Pu(e,t,i,s,r,o,n,a){return(r-n)*(t-a)>=(e-n)*(o-a)&&(e-n)*(s-a)>=(i-n)*(t-a)&&(i-n)*(o-a)>=(r-n)*(s-a)}function xu(e,t,i,s,r,o,n,a){return!(e===n&&t===a)&&Pu(e,t,i,s,r,o,n,a)}function Cu(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&&Fu(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Du(e,t)&&Du(t,e)&&function(e,t){let i=e,s=!1;const r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(Mu(e.prev,e,t.prev)||Mu(e,t.prev,t))||Eu(e,t)&&Mu(e.prev,e,e.next)>0&&Mu(t.prev,t,t.next)>0)}function Mu(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Eu(e,t){return e.x===t.x&&e.y===t.y}function Fu(e,t,i,s){const r=Tu(Mu(e,t,i)),o=Tu(Mu(e,t,s)),n=Tu(Mu(i,s,e)),a=Tu(Mu(i,s,t));return r!==o&&n!==a||(!(0!==r||!Iu(e,i,t))||(!(0!==o||!Iu(e,s,t))||(!(0!==n||!Iu(i,e,s))||!(0!==a||!Iu(i,t,s)))))}function Iu(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 Tu(e){return e>0?1:e<0?-1:0}function Du(e,t){return Mu(e.prev,e,e.next)<0?Mu(e,t,e.next)>=0&&Mu(e,e.prev,t)>=0:Mu(e,t,e.prev)<0||Mu(e,e.next,t)<0}function Su(e,t){const i=Lu(e.i,e.x,e.y),s=Lu(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function Ru(e,t,i,s){const r=Lu(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 Uu(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 Lu(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const ku=[0,1,0],Ou=[1,0,0],Nu=d.vec3(),Vu=d.vec3(),Qu=d.vec3(),Hu=d.vec3(),ju=d.vec3();function Gu(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 zu{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(((o,n)=>{if(!o)return;const a=s[n];if(!this._doesPlaneIntersectBoundingBox(a.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 l=this._sceneModelsData[e.id],A=l.modelOrigin;if(!l.verticesMap.has(n)){const e=a.meshes[0].isSolid(),t=[],i=[];e&&a.capMaterial&&(a.getEachVertex((e=>t.push(e[0]-A[0],e[1]-A[1],e[2]-A[2]))),a.getEachIndex((e=>i.push(e)))),l.verticesMap.set(n,t),l.indicesMap.set(n,i)}const c=l.verticesMap.get(n),h=l.indicesMap.get(n),u=-d.dotVec3(d.subVec3(t.pos,A,Nu),t.dir),p=[],f=h.length;for(let e=0;e<f;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],o=r[(e+1)%3],n=u+d.dotVec3(t.dir,s),a=u+d.dotVec3(t.dir,o);if(n*a>0)continue;const l=-n/(a-n);i.push(d.lerpVec3(l,0,1,s,o,d.vec3()))}2===i.length&&p.push(i)}p.length>0&&i.set(n,p)}));const o=new Map;i.forEach(((e,t)=>{o.set(t,[[e[0]]]),e.splice(0,1);let s=0;for(;e.length>0;){const r=o.get(t)[s][o.get(t)[s].length-1][1];let n=!1;for(let i=0;i<e.length;i++){const[a,l]=e[i];if(Gu(r,a)){o.get(t)[s].push(e[i]),e.splice(i,1),n=!0;break}if(Gu(r,l)){o.get(t)[s].push([l,a]),e.splice(i,1),n=!0;break}}if(!n&&Gu(r,o.get(t)[s][0][0])&&e.length>1)o.get(t).push([i.get(t)[0]]),e.splice(0,1),s++;else if(!n)break}}));const n=new Map;o.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)])}));n.set(i,s)}));const a=new Map;let l;n.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin;l=[];const o=i,n=[],A=new Set;for(let e=0;e<o.length;e++){if(A.has(e))continue;const t=[o[e]];A.add(e);for(let i=e+1;i<o.length;i++)A.has(i)||(this._isLoopInside(o[e],o[i])||this._isLoopInside(o[i],o[e]))&&(t.push(o[i]),A.add(i));n.push(t)}n.forEach((e=>{const i=[],s=[];let o=0;const n=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})),a=n.indexOf(Math.max(...n));e[a].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2}));for(let t=0;t<e.length;t++)t!==a&&(s.push(o/2),e[t].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2})));const A=hu(i,s),c=[];for(let e=0;e<A.length;e+=3){const s=[];for(let o=0;o<3;o++){const n=2*A[e+o],a=[i[n],i[n+1]],l=this._convertTo3D(a,t,r);s.push(l)}c.push(s)}l.push(c)})),a.set(s,l)}));const A=new Map;a.forEach(((e,t)=>{l=[],e.forEach((e=>{const t=new Map,i=[],s=[];let r=0;e.forEach((e=>{const o=[];e.forEach((e=>{const s=`${e[0].toFixed(6)},${e[1].toFixed(6)},${e[2].toFixed(6)}`;t.has(s)?o.push(t.get(s)):(i.push(e[0],e[1],e[2]),t.set(s,r),o.push(r),r++)})),s.push(...o)})),l.push({positions:i,indices:s})})),A.set(t,l)})),this._prevIntersectionModelsMap[e.id]||(this._prevIntersectionModelsMap[e.id]=new Map),d.mulVec3Scalar(t.dir,.001,ju),A.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin,o=new Array(i.size);let n=0;i.forEach(((i,a)=>{const l=i.positions,A=i.indices;l.length;const c=d.buildNormals(l,A),h=this._createUVs(l,t,r);o[n++]=new fs(this.scene,{id:`${t.id}-${s}-${a}`,geometry:new ve(this.scene,{primitive:"triangles",positions:l,indices:A,normals:c,uv:h}),origin:d.addVec3(r,ju,Nu),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(...o):this._prevIntersectionModelsMap[e.id].set(s,o)}))}))}))}_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 o=!1,n=!1;for(const e of r){const i=t.dist+d.dotVec3(t.dir,e);if(i>0&&(o=!0),i<0&&(n=!0),o&&n)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 fs(this.scene,{clippable:!1,geometry:new ve(this.scene,Oe({startPoint:e[0],endPoint:e[1]})),material:new bs(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),o=d.normalizeVec3(r);return[d.dotVec3(e,i),d.dotVec3(e,o)]}_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 o=t[e][0][0],n=t[e][0][1],a=t[r][0][0],l=t[r][0][1];n>i[1]!=l>i[1]&&i[0]<(a-o)*(i[1]-n)/(l-n)+o&&(s=!s)}return s}_convertTo3D(e,t,i){let s,r=t.dir,o=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 n=d.vec3(r),a=d.cross3Vec3(n,s),l=d.normalizeVec3(a),A=e[0],c=e[1],h=[s[0]*A+l[0]*c,s[1]*A+l[1]*c,s[2]*A+l[2]*c],u=d.dotVec3(r,[o[0]-h[0]-i[0],o[1]-h[1]-i[1],o[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=Nu;r.set(t.dir),d.normalizeVec3(r);const o=Vu,n=[];for(let t=0;t<e.length;t+=3){o[0]=e[t]+i[0],o[1]=e[t+1]+i[1],o[2]=e[t+2]+i[2];const a=d.subVec3(o,s,Qu),l=d.dotVec3(a,r);d.subVec3(o,d.mulVec3Scalar(r,l,Qu),o);const A=Math.abs(d.dotVec3(r,ku))<.999?d.cross3Vec3(r,ku,Qu):Ou,c=d.cross3Vec3(r,A,Qu);d.normalizeVec3(c,c);const h=d.subVec3(o,s,o);n.push(d.dotVec3(h,d.normalizeVec3(d.cross3Vec3(c,r,Hu))),d.dotVec3(h,c))}return n}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 Wu(e,t){const i={};let s,r;for(let o=0,n=t.length;o<n;o++)s=t[o],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 Xu extends R{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 gh(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}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Rh(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 Uh(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new ru(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new ou(this,{enabled:t.saoEnabled}),this.crossSections=new nu(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 Lh(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new iu(this,{id:"default.camera",dontClear:!0}),this._sectionCaps=new zu(this),new Uc(this,{color:[1,1,1],intensity:.7}),new kc(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new kc(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 "+y.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],y.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}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}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())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;r<i;r++)t.pass=r,this.fire("rendering",t,!0),o=s||0===r,this._renderer.render({pass:r,clear:o,force:e}),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:(!y.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:(!y.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:(!y.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"]||Ce(ve)}get material(){return this.components["default.material"]||new bs(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new Gs(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 Gs(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 Gs(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 Ws(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 lu(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 cu(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,o=d.MIN_DOUBLE,n=d.MIN_DOUBLE;const a=this._collidables;let l,A=!1;for(const c in a)if(a.hasOwnProperty(c)){if(l=a[c],!1===l.collidable)continue;e=l.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]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){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=Wu(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=Wu(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){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}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(y.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,o=d.MIN_DOUBLE,n=d.MIN_DOUBLE,a=d.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const l=e.aabb;l[0]<i&&(i=l[0]),l[1]<s&&(s=l[1]),l[2]<r&&(r=l[2]),l[3]>o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,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){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s<r;s++){const r=e[s];let o=this.objects[r];if(o)i=t(o)||i;else{const e=this.modelIds;for(let s=0,n=e.length;s<n;s++){const n=e[s],a=d.globalizeObjectId(n,r);o=this.objects[a],o&&(i=t(o)||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 o=function(...e){i=e,r++},n=this.on("tick",(()=>{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();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 Ku=d.vec4(),Zu=d.vec4(),Ju=d.vec3(),Yu=d.vec3(),qu=d.vec3(),$u=d.vec4(),ed=d.vec4(),td=d.vec4();class id{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,Ju);s=d.lenVec3(t)<i}if("perspective"===r.projection){r.ortho.scale=r.ortho.scale-i;const s=this._unproject(t,$u),o=d.subVec3(s,r.eye,td),n=d.mulVec3Scalar(d.normalizeVec3(o),-i,[]);if(r.eye=[r.eye[0]-n[0],r.eye[1]-n[1],r.eye[2]-n[2]],r.look=[r.look[0]-n[0],r.look[1]-n[1],r.look[2]-n[2]],e){const t=d.subVec3(e,r.eye,Ju),i=d.lenVec3(t),s=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,Yu)),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,$u);r.ortho.scale=r.ortho.scale-i,r.ortho._update();const s=this._unproject(t,ed),o=d.subVec3(s,e,td),n=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,Ju)),-i,Yu),a=d.addVec3(o,n,qu);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]]}return s}_unproject(e,t){const i=this._scene.camera,s=i.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o);return i.project.unproject(e,a,Ku,Zu,t),t}destroy(){}}const sd=d.vec3(),rd=d.vec3(),od=d.vec3(),nd=d.vec4(),ad=d.vec4(),ld=d.vec4(),Ad=Math.PI-.001;class cd{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),qe(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new we(this._scene,De({radius:s})),this._pivotSphere=new fs(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 o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(qe(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 bs(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,sd)),i=d.cross3Vec3(t,e.worldUp,rd);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),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=nd;t.project.unproject(e,a,ad,ld,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,sd)),c=d.addVec3(t.eye,d.mulVec3Scalar(A,i,rd),od);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 o=r<0,n=r>0,a=Math.abs(this._polar-.001)<.005,l=Math.abs(this._polar-Ad)<.005;let A=this._polar+.01*r;A=a&&o?.001:l&&n?Ad:d.clamp(A,.001,Ad),this._polar=A;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 p=d.lookAtMat4v(c,u,i.worldUp);p=d.inverseMat4(p);const f=d.transformVec3(p,this._cameraOffset);p[12]-=f[0],p[13]-=f[1],p[14]-=f[2];const m=[p[8],p[9],p[10]];i.eye=[p[12],p[13],p[14]],d.subVec3(i.eye,d.mulVec3Scalar(m,h),i.look),i.up=[p[4],p[5],p[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 hd{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 uh;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 ud=d.vec2();class dd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a,l,A,c=0,h=0,u=0,p=0,f=!1;const m=d.vec3();let g=!0;const _=this._scene.canvas.canvas,v=[];function b(e=!0){c=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],p=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(f=!0,m.set(o.pickResult.worldPos)):f=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!1}),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{v.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{v.splice(0)}),_.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:v[e.input.KEY_SHIFT]||i.planView?(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b()):(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b(!1));break;case 2:l=!0,v[e.input.MOUSE_MIDDLE_BUTTON]=!0,b();break;case 3:A=!0,v[e.input.MOUSE_RIGHT_BUTTON]=!0,i.panRightClick&&b()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!a&&!l&&!A)return;const o=e.canvas.boundary,u=o[2],p=o[3],g=s.pointerCanvasPos[0],_=s.pointerCanvasPos[1],b=i.planView||n._isKeyDownForAction(n.MOUSE_PAN,v),y=n._isKeyDownForAction(n.MOUSE_ROTATE,v),w=document.pointerLockElement?t.movementX:g-c,B=document.pointerLockElement?t.movementY:_-h;if(b){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(f?d.lenVec3(d.subVec3(m,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*w*i/p,r.panDeltaY+=1.5*B*i/p}else r.panDeltaX+=.5*t.ortho.scale*(w/p),r.panDeltaY+=.5*t.ortho.scale*(B/p)}else y&&(i.planView||(i.firstPerson?(r.rotateDeltaY-=w/u*i.dragRotationRate/2,r.rotateDeltaX+=B/p*(i.dragRotationRate/4)):(r.rotateDeltaY-=w/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=B/p*(1.5*i.dragRotationRate))));c=g,h=_}),_.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:case 2:case 3:a=!1,l=!1,A=!1,v[e.input.MOUSE_LEFT_BUTTON]=!1,v[e.input.MOUSE_MIDDLE_BUTTON]=!1,v[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,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,ud);const i=ud[0],s=ud[1];Math.abs(i-u)<3&&Math.abs(s-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:ud,event:e},!0)}_.style.removeProperty("cursor")}}),_.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const y=1/60;let w=null;_.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel&&n._isKeyDownForAction(n.MOUSE_DOLLY,v)))return;const t=performance.now()/1e3;var o=null!==w?t-w:0;w=t,o>.05&&(o=.05),o<y&&(o=y);const a=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===a)return;const l=a/Math.abs(a);r.dollyDelta+=-l*o*i.mouseWheelDollyRate,g&&(s.followPointerDirty=!0,g=!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 pd=d.vec3(),fd=d.vec3(),md=d.vec3(),gd=d.vec3(),_d=d.vec3(),vd={eye:d.vec3(),look:d.vec3(),up:d.vec3()};class bd{constructor(e,t,i,s){this._scene=e;const r=t.cameraControl,o=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),h=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||c||h))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,pd);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),m=1.1*p;vd.orthoScale=m,n?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldRight,f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):a?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldForward,f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):l?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldRight,-f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):A?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldForward,-f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):c?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldUp,f,fd),_d)),vd.look.set(pd),vd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,md),gd))):h&&(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldUp,-f,fd),_d)),vd.look.set(pd),vd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,md)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(pd),t.cameraFlight.duration>0?t.cameraFlight.flyTo(vd,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(vd),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class yd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;let l=!1,A=!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(l||A)return;if(a.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),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),h=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||h||u||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});c.addEventListener("mousemove",u),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!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&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot(),this._lastClickedWorldPos=t.worldPos.slice()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):this._lastClickedWorldPos?n.setPivotPos(this._lastClickedWorldPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||c)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(h(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.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 wd{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[];e.canvas.canvas;let a=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{a=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,t.pivotController.getPivoting()&&t.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{n.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{n.splice(0)}),this._onTick=e.on("tick",(l=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,c=l.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=c*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),a&&(s.followPointerDirty=!0,a=!1)}}const h=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),m=A._isKeyDownForAction(A.PAN_DOWN,n),g=(n[o.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(h||u||d||p||f||m)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=g:f&&(r.panDeltaY+=-g),p?r.panDeltaX+=-g:d&&(r.panDeltaX+=g),u?r.panDeltaZ+=g:h&&(r.panDeltaZ+=-g))}))}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 Bd=d.vec3();class Pd{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController,A=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&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(d.lenVec3(d.subVec3(u,e.camera.eye,Bd)));h=t/i.dollyProximityThreshold}h<i.dollyMinSpeed&&(h=i.dollyMinSpeed)}}else h=1,u=null;const p=r.dollyDelta*h;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(!i.firstPerson&&i.followPointer&&a.getPivoting()?(a.continuePivot(r.rotateDeltaY,r.rotateDeltaX),a.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?o.pitch(-r.rotateDeltaX):o.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?o.yaw(r.rotateDeltaY):o.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,t=A._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,n;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){o.xUp?(s=o.eye[0],n=o.look[0]):o.yUp?(s=o.eye[1],n=o.look[1]):o.zUp&&(s=o.eye[2],n=o.look[2]),o.pan(e);const t=o.eye,i=o.look;o.xUp?(t[0]=s,i[0]=n):o.yUp?(t[1]=s,i[1]=n):o.zUp&&(t[2]=s,i[2]=n),o.eye=t,o.look=i}else o.pan(e);t=A._cursors.pan}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==p){if(t=p<0?A._cursors.dollyForward:A._cursors.dollyBackward,i.firstPerson){let e,t;if(i.constrainVertical&&(o.xUp?(e=o.eye[0],t=o.look[0]):o.yUp?(e=o.eye[1],t=o.look[1]):o.zUp&&(e=o.eye[2],t=o.look[2])),i.followPointer){l.dollyToCanvasPos(u,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.pan([0,0,p]),o.ortho.scale=o.ortho.scale-p;if(i.constrainVertical){const i=o.eye,s=o.look;o.xUp?(i[0]=e,s[0]=t):o.yUp?(i[1]=e,s[1]=t):o.zUp&&(i[2]=e,s[2]=t),o.eye=i,o.look=s}}else if(i.planView)if(i.followPointer){l.dollyToCanvasPos(u,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);else if(i.followPointer){l.dollyToCanvasPos(u,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);r.dollyDelta*=i.dollyInertia}n.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class xd{constructor(e,t,i,s,r){this._scene=e;const o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Cd(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Cd(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.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 Cd(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 Md=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 Ed{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),c=d.vec2(),h=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Md(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));h.length<r.length;)h.push(d.vec2());for(let e=0,t=r.length;e<t;++e)Md(r[e],h[e]);p=r.length}),u.addEventListener("touchend",this._canvasTouchEndHandler=()=>{n.getPivoting()&&(n.endPivot(),n.hidePivot())}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],m=t.touches;if(t.touches.length===p){if(1===p){Md(m[0],l),d.subVec2(l,h[0],c);const t=c[0],o=c[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=m[0],n=m[1];Md(t,l),Md(n,A);const a=d.geometricMeanVec2(h[0],h[1]),c=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,c,p);const f=p[0],g=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(h[0],h[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.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-=f*s/u*i.touchPanRate,r.panDeltaY-=g*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(g/u)*i.touchPanRate;s.pointerCanvasPos=c}for(let e=0;e<p;++e)Md(m[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 Fd=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 Id{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a;const l=[],A=new Float32Array(2);let c=-1,h=-1;const u=this._scene.canvas.canvas,p=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,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,Fd(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,h=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(h)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else c=-1;for(;l.length<r.length;)l.push(new Float32Array(2));for(let e=0,t=r.length;e<t;++e)Fd(r[e],l[e]);l.length=r.length},{passive:!0}),u.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(h>-1&&c-h<325?(Fd(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),h=-1):d.distVec2(l[0],A)<4&&(Fd(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),h=t),c=-1),l.length=r.length;for(let e=0,t=r.length;e<t;++e)l[e][0]=r[e].pageX,l[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 Td extends R{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 hd(this,this._configs),pivotController:new cd(i,this._configs),panController:new id(i),cameraFlight:new se(this,{duration:.5})},this._handlers=[new xd(this.scene,this._controllers,this._configs,this._states,this._updates),new Ed(this.scene,this._controllers,this._configs,this._states,this._updates),new dd(this.scene,this._controllers,this._configs,this._states,this._updates),new bd(this.scene,this._controllers,this._configs,this._states,this._updates),new yd(this.scene,this._controllers,this._configs,this._states,this._updates),new Id(this.scene,this._controllers,this._configs,this._states,this._updates),new wd(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 Pd(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",y.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 Dd{constructor(e,t,i,s,r){this.name=e,this.type=i,this.value=t,this.valueType=s,this.description=r}}class Sd{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 Dd(i.name,i.value,i.type,i.valueType,i.description))}}}}class Rd{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,o=s.length;r<o;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,o=s.length;r<o;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 o=0,n=s.length;o<n;o++)e(s[o])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class Ud{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 Sd({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 o=i.metaObjects[r];if(!o){const e=s.type,t=s.originalSystemId,i=s.propertySets||s.propertySetIds;o=new Rd({id:r,originalSystemId:t,parentId:s.parent,type:e,name:s.name,attributes:s.attributes,propertySetIds:i,external:s.external}),this.metaScene.metaObjects[r]=o,o.metaModels=[]}this.metaObjects[r]=o,s.parent||(this.rootMetaObjects.push(o),i.rootMetaObjects[r]=o),o.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 o=e[r];o?t[s]=o: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 Ld{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 Ud({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],o=t&&t.length>0?kd(t):null,n=i&&i.length>0?kd(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r<l;r++)a(i[r])};return a(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function kd(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=!0;return t}
|
|
23
|
+
**/let ac=null;function lc(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const c=Math.min(r=ac[i],o=ac[i+1],n=ac[i+2]),h=Math.min(a=ac[s],l=ac[s+1],A=ac[s+2]);if(c!==h)return c-h;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let Ac=null;function cc(e,t){let i=Ac[2*e]-Ac[2*t];return 0!==i?i:Ac[2*e+1]-Ac[2*t+1]}function hc(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;ac=new Int32Array(e.length);for(let i=0,s=e.length;i<s;i++)ac[i]=e[i]>>t;i.sort(lc);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),o=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}Ac=new Int32Array(e),t.sort(cc);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 n(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=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<<t))return[e];const A=new Int32Array(l);A.fill(-1);const c=[];function h(){A.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 l=r[t],c=r[t+1],d=r[t+2];if(-1===A[l]&&i++,-1===A[c]&&i++,-1===A[d]&&i++,i+u.numPositions>u.maxNumPositions&&(u=h()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[c]&&(A[c]=u.numPositions++,u.positionsCompressed.push(s[3*c]),u.positionsCompressed.push(s[3*c+1]),u.positionsCompressed.push(s[3*c+2])),-1===A[d]&&(A[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(A[l]),u.indices.push(A[c]),u.indices.push(A[d]),(p=n(l,c))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(c,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let m=0,g=-s.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,g+=e.positionsCompressed.length/3})),m>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e<s;e+=3){const s=n[3*t[e]]+"_"+n[3*t[e]+1]+"_"+n[3*t[e]+2]+"/"+n[3*t[e+1]]+"_"+n[3*t[e+1]+1]+"_"+n[3*t[e+1]+2]+"/"+n[3*t[e+2]]+"_"+n[3*t[e+2]+1]+"_"+n[3*t[e+2]+2];i[s]=!0}r+=e.edgeIndices.length/2;for(let e=0,t=o.length;e<t;e+=2){const t=n[3*o[e]]+"_"+n[3*o[e]+1]+"_"+n[3*o[e]+2]+"/"+n[3*o[e+1]]+"_"+n[3*o[e+1]+1]+"_"+n[3*o[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 uc=new Float32Array([0,0,0]),dc=new Uint16Array([0,0,0]);d.OBB3();class pc{constructor(e,t,i,s,r,o){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=!!o,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(fr)}set visible(e){if(!!(this._flags&fr)!==e){this._flags=e?this._flags|fr:this._flags&~fr;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(yr)}set highlighted(e){if(!!(this._flags&yr)!==e){this._flags=e?this._flags|yr:this._flags&~yr;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(br)}set xrayed(e){if(!!(this._flags&br)!==e){this._flags=e?this._flags|br:this._flags&~br;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(wr)}set selected(e){if(!!(this._flags&wr)!==e){this._flags=e?this._flags|wr:this._flags&~wr;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(Br)}set edges(e){if(!!(this._flags&Br)!==e){this._flags=e?this._flags|Br:this._flags&~Br;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&mr)!==e){this._flags=e?this._flags|mr:this._flags&~mr;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(_r)}set clippable(e){if(!!(this._flags&_r)!==e){this._flags=e?this._flags|_r:this._flags&~_r;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(vr)}set collidable(e){if(!!(this._flags&vr)!==e){this._flags=e?this._flags|vr:this._flags&~vr;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(gr)}set pickable(e){if(!!(this._flags&gr)!==e){this._flags=e?this._flags|gr:this._flags&~gr;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 uc[0]=e[0]/255,uc[1]=e[1]/255,uc[2]=e[2]/255,uc}set colorize(e){if(e){dc[0]=Math.floor(255*e[0]),dc[1]=Math.floor(255*e[1]),dc[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(dc)}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 gs?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 fc=d.vec4(4),mc=d.vec4(),gc=d.vec4(),_c=d.vec3([1,0,0]),vc=d.vec3([0,1,0]),bc=d.vec3([0,0,1]);d.vec3(3),d.vec3(3);const yc=d.identityMat4();class wc{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||yc),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 fc[0]=e[0],fc[1]=e[1],fc[2]=e[2],fc[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(fc,mc),d.mulQuaternions(this.quaternion,mc,gc),this.quaternion=gc,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return fc[0]=e[0],fc[1]=e[1],fc[2]=e[2],fc[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(fc,mc),d.mulQuaternions(mc,this.quaternion,mc),this}rotateX(e){return this.rotate(_c,e)}rotateY(e){return this.rotate(vc,e)}rotateZ(e){return this.rotate(bc,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 Bc=d.vec3(),Pc=d.OBB3(),xc=d.vec4(),Cc=d.vec3([1,1,1]),Mc=d.vec3([0,0,0]);d.vec3([0,0,0]);const Ec=d.identityQuaternion(),Fc=d.identityMat4(),Ic=new Uint8Array([255,255,255]);class Tc extends R{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._vboBatchingLayerScratchMemory=(pr++,dr),this._textureTranscoder=t.textureTranscoder||ic(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=d.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},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 rs,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()})),this._createDefaultTextureSet(),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}_createDefaultTextureSet(){const e=new zA({id:"defaultColorTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new zA({id:"defaultMetalRoughTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new zA({id:"defaultNormalsTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new zA({id:"defaultEmissiveTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new zA({id:"defaultOcclusionTexture",texture:new Ps({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new GA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}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||Fc),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:_o(e.aabb,d.mat4())}:this.error("[createQuantizationRange] Config missing: id")}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)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!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=_o(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=go(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),me.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&&me.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=Ae(e.positions,e.indices,null,5):e.edgeIndices=Ae(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){const t=me.getUVBounds(e.uv),i=me.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 o=e.wrapT||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);let n=e.wrapR||1e3;1001!==n&&1002!==n&&1e3!==n&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),n=1e3);let a=e.encoding||3e3;3e3!==a&&3001!==a&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),a=3e3);const l=new Ps({gl:this.scene.canvas.gl,minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,encoding:a});if(e.preloadColor&&l.setPreloadColor(e.preloadColor),e.image){const t=e.image;if(t.crossOrigin="Anonymous",t.compressed){const e=t.data;l.setCompressedData({mipmaps:e,props:{format:e[0].format,minFilter:i,magFilter:s}})}else l.setImage(t,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const A=new Image;A.onload=()=>{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).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,l).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 zA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new GA({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}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 wc({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;if(!(void 0!==e.geometryId)){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)return this.error(`Unsupported value for 'primitive': '${primitive}' ('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||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' 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;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Cc,i=e.position||Mc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",xc),e.meshMatrix=d.composeMat4(i,xc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||Ec,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=_o(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Ic,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];$e(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=go(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),me.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();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&&me.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}e.meshMatrix&&(d.AABB3ToOBB3(e.aabb,Pc),d.transformOBB3(e.meshMatrix,Pc),d.OBB3ToAABB3(Pc,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=Ae(e.positions,e.indices,null,2):e.edgeIndices=Ae(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=Dc(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];$e(e.positions,t,Bc)&&(e.positions=t,e.origin=d.addVec3(e.origin,Bc,d.vec3()))}if(e.positions){const t=d.collapseAABB3();e.meshMatrix&&(d.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),d.expandAABB3Points3(t,e.positions),e.aabb=t}else{const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),me.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.meshMatrix&&(d.AABB3ToOBB3(e.aabb,Pc),d.transformOBB3(e.meshMatrix,Pc),d.OBB3ToAABB3(Pc,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=Ae(e.positions,e.indices,null,2):e.edgeIndices=Ae(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`),!1}}else{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[e.geometryId],!e.geometry)return this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`),!1;if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return this.error(`[createMesh] Transform not found: ${e.transformId} - ensure that you create it first with createTransform()`),!1;e.aabb=e.geometry.aabb}else{if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Cc,i=e.position||Mc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",xc),e.meshMatrix=d.composeMat4(i,xc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||Ec,t,d.mat4())}d.AABB3ToOBB3(e.geometry.aabb,Pc),d.transformOBB3(e.meshMatrix,Pc),e.aabb=d.OBB3ToAABB3(Pc,d.AABB3())}if(!(!this._dtxEnabled||"triangles"!==e.geometry.primitive&&"solid"!==e.geometry.primitive&&"surface"!==e.geometry.primitive||e.textureSetId)){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Ic,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=Dc(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Ic,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId])}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createDefaultIndices(e){const t=[];for(let i=0;i<e;i++)t.push(i);return t}_createMesh(e){const t=new ur(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);const i=t.pickId,s=i>>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_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 jA(this,{layerIndex:0,origin:t,primitive:i});break;case"lines":r=new vl(this,{layerIndex:0,origin:t,primitive:i});break;default:return}return this._dtxLayers[s]=r,this.layerList.push(r),this._layersToFinalize.push(r),r}_getVBOBatchingLayer(e){const t=this,i=e.origin;e.renderLayer;const s=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",r=e.textureSetId||"-",o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${e.primitive}.${s}.${r}`;let n=this._vboBatchingLayers[o];if(n)return n;let a=e.textureSet;for(;!n;){switch(e.primitive){case"triangles":case"solid":case"surface":n=new To({model:t,textureSet:a,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0,primitive:e.primitive});break;case"lines":n=new Hn({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive});break;case"points":n=new Fa({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive})}const s=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?n.canCreatePortion(s):n.canCreatePortion(s,e.indices.length))||(n.finalize(),delete this._vboBatchingLayers[o],n=null)}return this._vboBatchingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}_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)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Bn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Bn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new la({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new el({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}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 void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=fr),this._pickable&&!1!==e.pickable&&(t|=gr),this._culled&&!1!==e.culled&&(t|=mr),this._clippable&&!1!==e.clippable&&(t|=_r),this._collidable&&!1!==e.collidable&&(t|=vr),this._edges&&!1!==e.edges&&(t|=Br),this._xrayed&&!1!==e.xrayed&&(t|=br),this._highlighted&&!1!==e.highlighted&&(t|=yr),this._selected&&!1!==e.selected&&(t|=wr),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;i<s;i++){const s=e.meshIds[i];let r=this._meshes[s];r?r.parent?this.error(`Mesh with ID "${s}" already belongs to object with ID "${r.parent.id}" - ignoring this mesh`):(t.push(r),delete this._unusedMeshes[s]):this.error(`Mesh with this ID not found: "${s}" - ignoring this mesh`)}const i=new pc(this,e.isObject,e.id,t,e.flags,!0);return this._entityList.push(i),this._entities[e.id]=i,this._entitiesToFinalize.push(i),this.numEntities++,i}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._vboBatchingLayers={},this._vboInstancingLayers={},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)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t<s;t++){const s=i.visibleLayers[t];this.layerList[s].drawColorOpaque(i,e)}}drawColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawColorTransparent(t,e)}}drawDepth(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawDepth(t,e)}}drawNormals(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawNormals(t,e)}}drawSilhouetteXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteXRayed(t,e)}}drawSilhouetteHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteHighlighted(t,e)}}drawSilhouetteSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteSelected(t,e)}}drawEdgesColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorOpaque(t,e)}}drawEdgesColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorTransparent(t,e)}}drawEdgesXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesXRayed(t,e)}}drawEdgesHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesHighlighted(t,e)}}drawEdgesSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesSelected(t,e)}}drawOcclusion(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawOcclusion(t,e)}}drawShadow(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawShadow(t,e)}}setPickMatrices(e,t){if(0===this._numVisibleLayerPortions)return;const i=this.renderFlags;for(let s=0,r=i.visibleLayers.length;s<r;s++){const r=i.visibleLayers[s],o=this.layerList[r];o.setPickMatrices&&o.setPickMatrices(e,t)}}drawPickMesh(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickMesh(t,e)}}drawPickDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickDepths(t,e)}}drawPickNormals(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickNormals(t,e)}}drawSnapInit(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnapInit&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnapInit(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}drawSnap(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnap&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnap(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}destroy(){for(let e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();this._vboBatchingLayers={};for(let e in this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(e)&&this._vboInstancingLayers[e].destroy();this._vboInstancingLayers={},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),0!==pr&&(pr--,0===pr&&dr._clear()),super.destroy()}}function Dc(e,t,i){let s,r,o,n;if(t||i?[s,r,o]=nc({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(s=e.positionsCompressed,r=e.indices,o=e.edgeIndices),i){n=hc({positionsCompressed:s,indices:r,edgeIndices:o},s.length/3>65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class Sc extends R{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 Tc(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 Rc extends R{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Uc extends Rc{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 Lc{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),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),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),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_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),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e<r.length;e++)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+e,s.TEXTURE_2D,r[e],0);if(e.length>0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))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={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,i||c.RGBA,s||c.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,c=new Uint8Array(4*n);for(let e=0;e<l;++e){const t=e*A,s=(a-e-1)*A;c.set(i.subarray(t,t+A)),i.copyWithin(t,s,s+A),i.set(c,s)}return r.data.set(i),o.putImageData(r,0,0),s}readImage(e){const t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,o=i.imageData,n=i.context,{width:a,height:l}=this.buffer;t.readPixels(0,0,a,l,t.RGBA,t.UNSIGNED_BYTE,s),o.data.set(s),n.putImageData(o,0,0),n.save(),n.globalCompositeOperation="copy",n.scale(1,-1),n.drawImage(r,0,-l,a,l),n.restore();let A=e.format||"png";return"jpeg"!==A&&"png"!==A&&"bmp"!==A&&(console.error("Unsupported image format: '"+A+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),A="png"),r.toDataURL(`image/${A}`)}_getImageDataCache(e=Uint8Array,t=4){const i=this.buffer.width,s=this.buffer.height;let r=this._imageDataCache;if(r&&(r.width===i&&r.height===s||(this._imageDataCache=null,r=null)),!r){const o=document.createElement("canvas"),n=o.getContext("2d");o.width=i,o.height=s,r={pixelData:new e(i*s*t),canvas:o,context:n,imageData:n.createImageData(i,s),width:i,height:s},this._imageDataCache=r}return r.context.resetTransform(),r}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(e=0){const t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}hasDepthTexture(){return this._hasDepthTexture}getDepthTexture(){if(!this._hasDepthTexture)return null;const e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}destroy(){if(this.allocated){const e=this.gl;this.buffer.textures.forEach((t=>e.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class kc extends Rc{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 ae({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 Lc(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[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 Oc extends Rc{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 ae({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 Lc(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[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 Nc(e){if(!Vc(e.width)||!Vc(e.height)){const t=document.createElement("canvas");t.width=Qc(e.width),t.height=Qc(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Vc(e){return 0==(e&e-1)}function Qc(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Hc extends R{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new ae({texture:new Ps({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),g.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}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o<e.length;o++){const n=new Image;n.onload=function(){let e=n;const a=o;return function(){if(!s&&(e=Nc(e),t._images[a]=e,r++,6===r)){let e=t._state.texture;e||(e=new Ps({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()}}}(),n.onerror=function(){s=!0},n.src=e[o]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),g.memory.textures--,this._state.destroy()}}class jc extends Hc{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 Gc extends Hc{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}}const zc=d.vec4(),Wc=d.vec4();class Xc extends R{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){zc.set(this._viewPos),zc[3]=1,d.transformPoint4(this.scene.camera.projMatrix,zc,Wc);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+Wc[0]/Wc[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-Wc[1]/Wc[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]),qe(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 Kc extends Xc{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 Is(this,{src:t.src}),this._geometry=new ve(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 fs(this,{geometry:this._geometry,material:new bs(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 Zc{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 Jc=d.vec3();class Yc{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?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!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),o&&(this.objectsXrayed[e]=t.xrayed),n&&(this.objectsHighlighted[e]=t.highlighted),a&&(this.objectsSelected[e]=t.selected),l&&(this.objectsClippable[e]=t.clippable),A&&(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,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!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]),o&&(t.xrayed=this.objectsXrayed[e]),n&&(t.highlighted=this.objectsHighlighted[e]),a&&(t.selected=this.objectsSelected[e]),l&&(t.clippable=this.objectsClippable[e]),A&&(t.pickable=this.objectsPickable[e]),c&&(Jc[0]=this.objectsColorize[3*e+0],Jc[1]=this.objectsColorize[3*e+1],Jc[2]=this.objectsColorize[3*e+2],t.colorize=Jc),h&&(t.opacity=this.objectsOpacity[e]))}}}const qc=d.vec3();class $c{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?y.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!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),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(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,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!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]),o&&(t.highlighted=this.objectsHighlighted[h]),n&&(t.selected=this.objectsSelected[h]),a&&(t.clippable=this.objectsClippable[h]),l&&(t.pickable=this.objectsPickable[h]),A&&(this.objectsHasColorize[h]?(qc[0]=this.objectsColorize[3*h+0],qc[1]=this.objectsColorize[3*h+1],qc[2]=this.objectsColorize[3*h+2],t.colorize=qc):t.colorize=null),c&&(t.opacity=this.objectsOpacity[h]),h++}}}class eh 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 th 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 o(){r._dirty=!0}function n(){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],y.isNumeric(t)||y.isString(t)){var a=t;if(!(t=this.scene.components[a])){this.error("Component not found: "+_inQuotes(a));continue}}var l=t.type;"xeokit.SplineCurve"===l||"xeokit.Path"===l||"xeokit.CubicBezierCurve"===l||"xeokit.QuadraticBezierCurve"===l?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",o)),this._destroyedSubs.push(t.once("destroyed",n))):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 o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}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 ih 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 sh extends Tc{constructor(e,t={}){super(e,t)}}const rh=d.vec3(),oh=d.vec3(),nh=d.vec4(),ah=d.vec3([0,0,-1]),lh=d.vec3([0,0,1]),Ah=d.vec3([0,1,0]);class ch extends R{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new ae({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,lh,this._state.dir);const t=d.vec3ApplyQuaternion(this._state.quaternion,Ah,rh),i=d.vec3PairToQuaternion(lh,this._state.dir,nh),s=d.vec3ApplyQuaternion(i,Ah,oh),r=Math.acos(Math.min(1,d.dotVec3(t,s))),o=Math.sign(d.dotVec3(this._state.dir,d.cross3Vec3(t,s,oh)));this._state.roll=o*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||ah),this._onDirRollUpdated()}_onDirRollUpdated(){d.vec3PairToQuaternion(lh,this._state.dir,this._state.quaternion),nh[0]=0,nh[1]=0,nh[2]=-1,nh[3]=this._state.roll,d.angleAxisToQuaternion(nh,nh),d.mulQuaternions(this._state.quaternion,nh,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 hh{transcode(e,t,i={}){}destroy(){}}class uh{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 dh={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 ph{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 o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}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 fh extends R{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 mh=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class gh extends R{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;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);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 fh(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<mh.length;e++)try{this.gl=this.canvas.getContext(mh[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,s){return this.scene._renderer.readPixels(e,t,i,s)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class _h{constructor(e){this._scene=e,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,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.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=d.vec3(),this.snapPickOrigin=d.vec3()}getRTCViewMatrix(e,t){let i=this._rtcViewMats[e];return i||(i=this._getNewMat(),Ye(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}getRTCPickViewMatrix(e,t){let i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();const s=this.pickViewMatrix||this._scene.camera.viewMatrix;Ye(s,t,i),this._rtcPickViewMats[e]=i}return i}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=d.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}class vh{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.vec3(t),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.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,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(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t<this.numMarkers;t++)if(this.markerList[t]){const i=this.markerList[t].rtcPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}_buildAABB(){const e=this.aabb;d.collapseAABB3(e),d.expandAABB3Points3(e,this.positions);const t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}_buildVBOs(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(new Float32Array(this.positions));this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,i=this.numMarkers;this.positionsBuf=new le(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new le(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,s=i[2],r=i[3];let o=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const i=this.markerList[e];if(i.viewPos[2]>-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i];if(t.active){const e=d.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const s=0===e;this.sectionPlanesActive[i]=s}else this.sectionPlanesActive[i]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const bh=d.vec3([1,0,0]),yh=d.vec3();class wh{constructor(e,t){this._scene=e,this._renderBufferManager=t,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=e.camera.on("viewMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new vh(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new vh(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildOcclusionLayersList(){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ci(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState,r=e.camera,o=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,i=this._occlusionLayersList.length;e<i;e++){const i=this._occlusionLayersList[e];if(i.update(),i.culledBySectionPlanes)continue;const o=i.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,Ye(r.viewMatrix,o));const n=s.sectionPlanes.length;if(n>0){const e=s.sectionPlanes;for(let s=0;s<n;s++){const r=this._uSectionPlanes[s];if(r){const n=i.sectionPlanesActive[s];if(t.uniform1i(r.active,n?1:0),n){const i=e[s];t.uniform3fv(r.pos,tt(i.dist,i.dir,o,yh)),t.uniform3fv(r.dir,i.dir)}}}}this._aPosition.bindArrayBuffer(i.positionsBuf);const a=i.indicesBuf;a.bind(),t.drawElements(t.POINTS,a.numItems,a.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*bh[0],i=255*bh[1],s=255*bh[2];for(let r=0,o=this._occlusionLayersList.length;r<o;r++){const o=this._occlusionLayersList[r];for(let r=0;r<o.lenOcclusionTestList;r++){const n=o.occlusionTestList[r],a=2*r,l=this._readPixelBuf.read(Math.round(o.pixels[a]*e),Math.round(o.pixels[a+1]*e)),A=l[0]===t&&l[1]===i&&l[2]===s;n._setVisible(A)}}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){if(!this.destroyed){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}const Bh=d.vec2();class Ph{constructor(e){this._scene=e,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){this._rebuild=!0}render(e){if(this._build(),this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,c=a.matrix,h=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;Bh[0]=o,Bh[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,h),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Bh),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e&&!this._rebuild)return;this._rebuild=!1;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ci(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new le(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new le(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new le(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const xh=new Float32Array(Th(17,[0,1])),Ch=new Float32Array(Th(17,[1,0])),Mh=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(Ih(s,t));return i}(17,4)),Eh=new Float32Array(2);class Fh{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Ci(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new le(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new le(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new le(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,c=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),Eh[0]=n,Eh[1]=a,s.uniform2fv(this._uViewport,Eh),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,c),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Ch):s.uniform2fv(this._uSampleOffsets,xh),s.uniform1fv(this._uSampleWeights,Mh);const h=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,h,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Ih(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Th(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class Dh{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new Lc(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}const Sh=d.vec3([0,0,0]),Rh=function(t,i){i=i||{};const s=new _h(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},c={},h=[],u=[],p=[],f=!0,m=!0,_=!0,v=!0,b=!0,y=!0,w=!0,B=!0;const P=new Dh(t);let x=!1;const C=new Ph(t),M=new Fh(t);function E(){f&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),f=!1,m=!0),m&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;t<s;t++){const s=i[t];h[e++]=s}}h.length=e,h.sort(((e,t)=>e.renderOrder-t.renderOrder))}(),m=!1,_=!0),_&&function(){let e=0,t=0;for(let i=0,s=h.length;i<s;i++){const s=h[i];s.rebuildRenderFlags(),s.renderFlags.culled||(s.isUI?p[t++]=s:u[e++]=s)}u.length=e,p.length=t}()}function F(e){if(!e.castsShadow)return;const t=e.getShadowRenderBuf();if(t){t.bind(),s.reset(),s.backfaces=!0,s.frontface=!0,s.shadowViewMatrix=e.getShadowViewMatrix(),s.shadowProjMatrix=e.getShadowProjMatrix(),o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,1),o.enable(o.DEPTH_TEST),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];!1!==i.visible&&i.castsShadow&&i.drawShadow&&(i.renderFlags.colorOpaque&&i.drawShadow(s))}}t.unbind()}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!ys(o,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!ys(o,"WEBGL_compressed_texture_etc"),dxtSupported:!!ys(o,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!ys(o,"EXT_texture_compression_bptc"),pvrtcSupported:!(!ys(o,"WEBGL_compressed_texture_pvrtc")&&!ys(o,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){v=e,_=!0},this.setEdgesEnabled=function(e){b=e,_=!0},this.setSAOEnabled=function(e){y=e,_=!0},this.setPBREnabled=function(e){w=e,_=!0},this.setColorTextureEnabled=function(e){B=e,_=!0},this.needStateSort=function(){m=!0},this.shadowsDirty=function(){},this.imageDirty=function(){_=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){C.init(),M.init(),_=!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=A[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},A[i]=s),s.count++,s.drawableMap[e]=t,c[e]=t,f=!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=A[i];--s.count<=0?delete A[i]:delete s.drawableMap[e],delete c[e],f=!0},this.getPickID=function(e){return l.addItem(e)},this.putPickID=function(e){l.removeItem(e)},this.clear=function(e){if(o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT)},this.needsRender=function(){return _||f||m},this.render=function(e){(e=e||{}).force&&(_=!0),E(),_&&(!function(e){const i=t.sao;y&&i.possible&&function(e){const i=t.sao,r=P.getRenderBuffer("saoDepth",{depthTexture:!0});r.bind(),r.clear(),function(e){s.reset(),s.pass=e.pass,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=u.length;e<t;e++){const t=u[e];!0!==t.culled&&!1!==t.visible&&t.drawDepth&&t.saoEnabled&&(t.renderFlags.colorOpaque&&t.drawDepth(s))}}(e),r.unbind();const n=P.getRenderBuffer("saoOcclusion");if(n.bind(),n.clear(),C.render(r),n.unbind(),i.blur){const e=P.getRenderBuffer("saoOcclusion2");e.bind(),e.clear(),M.render(r,n,0),e.unbind(),n.bind(),n.clear(),M.render(r,e,1),n.unbind()}}(e);(function(){let e=t._lightsState.lights;for(let t=0,i=e.length;t<i;t++){const i=e[t];i.castsShadow&&F(i)}})(),function(e){const i=[],r=[],l=[],A=[],c=[],h=[],f=[],m=[],_=[],x=[],C=[],M=[],E=[],F=[],I=[],T=[],D=t._lightsState.getAmbientColorAndIntensity();if(s.reset(),s.pass=e.pass,s.withSAO=!1,s.pbrEnabled=w&&!!t.pbrEnabled,s.colorTextureEnabled=B&&!!t.colorTextureEnabled,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?D:t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),o.lineWidth(1),s.lineWidth=1;const S=t.sao.possible;if(y&&S){const e=P.getRenderBuffer("saoOcclusion");s.occlusionTexture=e?e.getTexture():null}else s.occlusionTexture=null;let R,U;const L=Date.now();!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const k=function(e){let u=0,p=0,g=0,w=0,B=0,P=0,D=0,L=0,k=0,O=0,N=0,V=0,Q=0,H=0,j=0,G=0;for(let t=0,o=e.length;t<o;t++){if(U=e[t],!0===U.culled||!1===U.visible)continue;const o=U.renderFlags;o.colorOpaque&&(y&&S&&U.saoEnabled?i[u++]=U:U.drawColorOpaque(s)),v&&o.colorTransparent&&(l[g++]=U),o.xrayedSilhouetteTransparent&&(f[D++]=U),o.xrayedSilhouetteOpaque&&(c[B++]=U),o.highlightedSilhouetteTransparent&&(C[N++]=U),o.highlightedSilhouetteOpaque&&(_[k++]=U),o.selectedSilhouetteTransparent&&(I[j++]=U),o.selectedSilhouetteOpaque&&(E[Q++]=U),U.edges&&b&&(o.edgesOpaque&&(r[p++]=U),o.edgesTransparent&&(A[w++]=U),o.selectedEdgesTransparent&&(T[G++]=U),o.selectedEdgesOpaque&&(F[H++]=U),o.xrayedEdgesTransparent&&(m[L++]=U),o.xrayedEdgesOpaque&&(h[P++]=U),o.highlightedEdgesTransparent&&(M[V++]=U),o.highlightedEdgesOpaque&&(x[O++]=U))}if(u>0)for(s.withSAO=!0,R=0;R<u;R++)i[R].drawColorOpaque(s);if(p>0)for(R=0;R<p;R++)r[R].drawEdgesColorOpaque(s);if(B>0)for(R=0;R<B;R++)c[R].drawSilhouetteXRayed(s);if(P>0)for(R=0;R<P;R++)h[R].drawEdgesXRayed(s);if(D>0||L>0||g>0||w>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(g>0||w>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),w>0)for(R=0;R<w;R++)U=A[R],U.drawEdgesColorTransparent(s);if(g>0){const e=s.pickOrigin||t.camera.eye,i=l.map((t=>({drawable:t,distSq:d.distVec3(t.origin||Sh,e)})));for(i.sort(((e,t)=>t.distSq-e.distSq)),R=0;R<g;R++)i[R].drawable.drawColorTransparent(s)}if(L>0)for(R=0;R<L;R++)m[R].drawEdgesXRayed(s);if(D>0)for(R=0;R<D;R++)f[R].drawSilhouetteXRayed(s);o.disable(o.BLEND),a||o.depthMask(!0)}if(k>0||O>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),O>0)for(R=0;R<O;R++)x[R].drawEdgesHighlighted(s);if(k>0)for(R=0;R<k;R++)_[R].drawSilhouetteHighlighted(s)}if(N>0||V>0||k>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),V>0)for(R=0;R<V;R++)M[R].drawEdgesHighlighted(s);if(N>0)for(R=0;R<N;R++)C[R].drawSilhouetteHighlighted(s);o.disable(o.BLEND)}if(Q>0||H>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),H>0)for(R=0;R<H;R++)F[R].drawEdgesSelected(s);if(Q>0)for(R=0;R<Q;R++)E[R].drawSilhouetteSelected(s)}if(j>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),G>0)for(R=0;R<G;R++)T[R].drawEdgesSelected(s);if(j>0)for(R=0;R<j;R++)I[R].drawSilhouetteSelected(s);o.disable(o.BLEND)}};k(u),p.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),k(p));const O=Date.now(),N=g.frame;N.renderTime=(O-L)/1e3,N.drawElements=s.drawElements,N.drawArrays=s.drawArrays,N.useProgram=s.useProgram,N.bindTexture=s.bindTexture,N.bindArray=s.bindArray;const V=Mi.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<V;e++)o.activeTexture(o.TEXTURE0+e);o.bindTexture(o.TEXTURE_CUBE_MAP,null),o.bindTexture(o.TEXTURE_2D,null);const Q=Mi.MAX_VERTEX_ATTRIBS;for(let e=0;e<Q;e++)o.disableVertexAttribArray(e)}(e)}(e),g.frame.frameCount++,_=!1)},this.pick=function(){const e=d.vec3();d.mat4();const i=d.mat4(),n=d.vec3(),a=d.vec3([0,1,0]),c=new uh,h=d.vec2(),f=d.vec3(),m=d.vec3(),g=d.vec3();return d.vec3(),d.vec3(),function(_,v=c){let b;v.reset(),E();let y=null,w=null,B=null;v.pickSurface=_.pickSurface,_.canvasPos?(f[0]=_.canvasPos[0],f[1]=_.canvasPos[1],y=t.camera.viewMatrix,w=t.camera.projMatrix,B=t.camera.projection,h[0]=t.camera.project.near,h[1]=t.camera.project.far,v.canvasPos=_.canvasPos):(_.matrix?(y=_.matrix,w=t.camera.projMatrix,B=t.camera.projection,h[0]=t.camera.project.near,h[1]=t.camera.project.far):(m.set(_.origin||[0,0,0]),g.set(_.direction||[0,0,1]),b=d.addVec3(m,g,e),n[0]=Math.random(),n[1]=Math.random(),n[2]=Math.random(),d.normalizeVec3(n),d.cross3Vec3(g,n,a),y=d.lookAtMat4v(m,b,a,i),w=t.camera.ortho.matrix,B="ortho",h[0]=t.camera.ortho.near,h[1]=t.camera.ortho.far,v.origin=m,v.direction=g),f[0]=.5*r.clientWidth,f[1]=.5*r.clientHeight);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(y,w)}}const x=P.getRenderBuffer("pick",{size:[1,1]});x.bind();const C=function(e,i,r,n,a,A){const c=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=A.origin,s.pickViewMatrix=r,s.pickProjMatrix=n,s.pickInvisible=!!a.pickInvisible,s.pickClipPos=[D(i[0]*c,o.drawingBufferWidth),S(i[1]*c,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const h=a.includeEntityIds,d=a.excludeEntityIds,f=function(e){for(let t=0,i=e.length;t<i;t++){const i=e[t];!0!==i.culled&&!1!==i.visible&&(!i.drawPickMesh||!0!==a.pickInvisible&&!1===i.visible||!1===i.pickable||h&&!h[i.id]||d&&d[i.id]||i.drawPickMesh(s))}};f(u),p.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),f(p));const m=e.read(0,0),g=m[0]+(m[1]<<8)+(m[2]<<16)+(m[3]<<24);if(g<0)return;return l.items[g]}(x,f,y,w,_,v);if(!C)return x.unbind(),null;const M=C.delegatePickedEntity?C.delegatePickedEntity():C;return M?(_.pickSurface&&(C.canPickTriangle&&C.canPickTriangle()?(!function(e,i,r,n,a,l){if(!i.drawPickTriangles)return;const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),i.drawPickTriangles(s);const c=e.read(0,0);let h=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;h*=3,l.primIndex=h}(x,C,f,y,w,v),C.pickTriangleSurface(y,w,B,v),v.pickSurfacePrecision=!1):C.canPickWorldPos&&C.canPickWorldPos()&&(I(x,C,f,y,w,h,v),!1!==_.pickSurfaceNormal&&function(e,i,r,n,a,l){const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)];const c=P.getRenderBuffer("pick-normal",{size:[3,3]});c.bind(o.RGBA32I),o.viewport(0,0,c.size[0],c.size[1]),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),i.drawPickNormals(s);const h=c.read(1,1,o.RGBA_INTEGER,o.INT,Int32Array,4);c.unbind();const u=[h[0]/d.MAX_INT,h[1]/d.MAX_INT,h[2]/d.MAX_INT];d.normalizeVec3(u),l.worldNormal=u}(0,C,f,y,w,v),v.pickSurfacePrecision=!1)),x.unbind(),v.entity=M,v):(x.unbind(),null)}}();const I=function(){const e=d.vec4(),i=d.vec4(),n=d.vec4(),a=d.vec4(),l=d.vec4(),A=d.mat4(),c=d.mat4(),h=d.mat4();return function(u,p,f,m,g,_,v){const b=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=v.origin,s.pickViewMatrix=m,s.pickProjMatrix=g,s.pickZNear=_[0],s.pickZFar=_[1],s.pickElementsCount=p.pickElementsCount,s.pickElementsOffset=p.pickElementsOffset,s.pickClipPos=[D(f[0]*b,o.drawingBufferWidth),S(f[1]*b,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),p.drawPickDepths(s);const y=function(e){const t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],i=[1/16777216,1/65536,1/256,1];return d.dotVec4(t,i)}(u.read(0,0)),w=(f[0]-r.clientWidth/2)/(r.clientWidth/2),B=-(f[1]-r.clientHeight/2)/(r.clientHeight/2),P=p.origin;let x;if(P){const e=Ye(m,P,A);x=d.mulMat4(g,e,c)}else x=d.mulMat4(g,m,c);const C=d.inverseMat4(x,h);e[0]=w,e[1]=B,e[2]=-1,e[3]=1;let M=d.transformVec4(C,e);M=d.mulVec4Scalar(M,1/M[3]),i[0]=w,i[1]=B,i[2]=1,i[3]=1;let E=d.transformVec4(C,i);E=d.mulVec4Scalar(E,1/E[3]);const F=d.subVec3(E,M,n),I=d.addVec3(M,d.mulVec4Scalar(F,y,a),l);P&&d.addVec3(I,P),v.worldPos=I}}();function T(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(let t=0,i=u.length;t<i;t++){const i=u[t];i.drawSnapInit&&i.drawSnap&&!i.culled&&i.visible&&i.pickable&&i.drawSnap(e)}return e.snapPickLayerParams}function D(e,t){return e/t*2-1}function S(e,t){return 1-e/t*2}this.snapPick=function(){const e=new uh;return function(i,r=e){const{canvasPos:n,origin:a,direction:c,snapRadius:h,snapToVertex:p,snapToEdge:f}=i;if(!p&&!f)return this.pick({canvasPos:n,pickSurface:!0});const m=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickZNear=t.camera.project.near,s.pickZFar=t.camera.project.far;const g=h||30,_=P.getRenderBuffer(`uniquePickColors-aabs-${g}`,{depthTexture:!0,size:[2*g+1,2*g+1]});s.snapVectorA=[n?D(n[0]*m,o.drawingBufferWidth):0,n?S(n[1]*m,o.drawingBufferHeight):0],s.snapInvVectorAB=[o.drawingBufferWidth/(2*g),o.drawingBufferHeight/(2*g)],_.bind(o.RGBA32I,o.RGBA32I,o.RGBA8UI),o.viewport(0,0,_.size[0],_.size[1]),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.disable(o.CULL_FACE),o.depthMask(!0),o.disable(o.BLEND),o.depthFunc(o.LEQUAL),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),o.clearBufferiv(o.COLOR,1,new Int32Array([0,0,0,0])),o.clearBufferuiv(o.COLOR,2,new Uint32Array([0,0,0,0])),s.pickViewMatrix=n?t.camera.viewMatrix:d.lookAtMat4v(a,d.addVec3(a,c,d.vec3()),d.vec3([0,1,0]),d.mat4());const v=t.camera.projMatrix;for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(s.pickViewMatrix,v)}}o.drawBuffers([o.COLOR_ATTACHMENT0,o.COLOR_ATTACHMENT1,o.COLOR_ATTACHMENT2]);const b=function(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(let t=0,i=u.length;t<i;t++){const i=u[t];i.drawSnapInit&&!i.culled&&i.visible&&i.pickable&&i.drawSnapInit(e)}return e.snapPickLayerParams}(s),y=[];s.snapPickLayerParams=y,o.depthMask(!1),o.drawBuffers([o.COLOR_ATTACHMENT0]),p&&f?(s.snapMode="edge",T(s),s.snapMode="vertex",s.snapPickLayerNumber++,T(s)):(s.snapMode=p?"vertex":"edge",T(s)),o.depthMask(!0);const w=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4),B=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4,1),x=_.readArray(o.RGBA_INTEGER,o.UNSIGNED_INT,Uint32Array,4,2);_.unbind();let C=null,M=null,E=null;const F=4*g+g*_.size[0]*4,I=w.slice(F,F+4),R=B.slice(F,F+4),U=x.slice(F,F+4);if(0!==I[3]){const e=b[Math.abs(I[3])%b.length],t=e.origin,i=e.coordinateScale;C=[I[0]*i[0]+t[0],I[1]*i[1]+t[1],I[2]*i[2]+t[2]],M=d.normalizeVec3([R[0]/d.MAX_INT,R[1]/d.MAX_INT,R[2]/d.MAX_INT]);const s=U[0]+(U[1]<<8)+(U[2]<<16)+(U[3]<<24);E=l.items[s]}let L=[];for(let e=0;e<w.length;e+=4)if(w[e+3]>0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));L.push({x:s,y:r,dist:o,isVertex:p&&f?w[e+3]>y.length/2:p,result:[w[e+0],w[e+1],w[e+2],w[e+3]],normal:[B[e+0],B[e+1],B[e+2],B[e+3]],id:[x[e+0],x[e+1],x[e+2],x[e+3]]})}let k=null,O=null,N=null,V=null;if(L.length>0){L.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),V=L[0].isVertex?"vertex":"edge";const e=L[0].result,t=L[0].normal,i=L[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;O=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),k=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==k)return null;let Q=null;null!==k&&(Q=t.camera.projectWorldPos(k));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&E&&(E=E.delegatePickedEntity?E.delegatePickedEntity():E),r.reset(),r.snappedToEdge="edge"===V,r.snappedToVertex="vertex"===V,r.worldPos=k||C,r.worldNormal=O||M,r.entity=H||E,r.canvasPos=n||t.camera.projectWorldPos(C||k),r.snappedCanvasPos=Q||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new wh(t,P),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){E(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=u.length;e<t;e++){const t=u[e];t.drawOcclusion&&!0!==t.culled&&!1!==t.visible&&!1!==t.pickable&&t.drawOcclusion(s)}this._occlusionTester.drawMarkers(s),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,s){const r=P.getRenderBuffer("snapshot");let o,n,a,l;for(r.bind(),r.clear(),this.render({force:!0,opaqueOnly:s}),n=0;n<i;n++)a=2*n,l=4*n,o=r.read(e[a],e[a+1]),t[l]=o[0],t[l+1]=o[1],t[l+2]=o[2],t[l+3]=o[3];r.unbind(),_=!0},this.beginSnapshot=function(e={}){const t=P.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),x=!0},this.renderSnapshot=function(){if(!x)return;P.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),_=!0},this.readSnapshot=function(e){return P.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return P.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){if(!x)return;P.getRenderBuffer("snapshot").unbind(),x=!1},this.destroy=function(){A={},c={},P.destroy(),C.destroy(),M.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class Uh extends R{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 Lh extends R{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new ae({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 kh extends R{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Oh extends R{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Nh extends R{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Vh extends R{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ae({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 o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,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 Qh=d.vec3(),Hh=d.vec3(),jh=d.vec3(),Gh=d.vec3(),zh=d.vec3(),Wh=d.vec3(),Xh=d.vec4(),Kh=d.vec4(),Zh=d.vec4(),Jh=d.mat4(),Yh=d.mat4(),qh=d.vec3(),$h=d.vec3(),eu=d.vec3(),tu=d.vec3();class iu extends R{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new ae({offsetEyeFromLook:!0,deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new kh(this),this._ortho=new Oh(this),this._frustum=new Nh(this),this._customProjection=new Vh(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,qh),d.normalizeVec3(qh,$h),d.mulVec3Scalar($h,1e3,eu),d.addVec3(this._look,eu,tu),t=tu):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Yh),d.mulMat4(e.deviceMatrix,Yh,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,Qh);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Jh),t=d.transformPoint3(Jh,t,Hh),this.eye=d.addVec3(this._look,t,jh),this.up=d.transformPoint3(Jh,this._up,Gh)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,Qh);const i=d.cross3Vec3(d.normalizeVec3(t,Hh),d.normalizeVec3(this._up,jh));d.rotationMat4v(.0174532925*e,i,Jh),t=d.transformPoint3(Jh,t,Gh),this.up=d.transformPoint3(Jh,this._up,zh),this.eye=d.addVec3(t,this._look,Wh)}yaw(e){let t=d.subVec3(this._look,this._eye,Qh);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Jh),t=d.transformPoint3(Jh,t,Hh),this.look=d.addVec3(t,this._eye,jh),this._gimbalLock&&(this.up=d.transformPoint3(Jh,this._up,Gh))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,Qh);const i=d.cross3Vec3(d.normalizeVec3(t,Hh),d.normalizeVec3(this._up,jh));d.rotationMat4v(.0174532925*e,i,Jh),this.up=d.transformPoint3(Jh,this._up,Wh),t=d.transformPoint3(Jh,t,Gh),this.look=d.addVec3(t,this._eye,zh)}pan(e){const t=d.subVec3(this._eye,this._look,Qh),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,Hh));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,jh),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,Gh),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,zh),this.look=d.addVec3(this._look,i,Wh)}zoom(e){const t=d.subVec3(this._eye,this._look,Qh),i=Math.abs(d.lenVec3(t,Hh)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,jh);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),Gh)}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,Qh))}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=Xh,i=Kh,s=Zh;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,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}const su={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 ru extends R{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 su}set units(e){e||(e="meters");su[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 ou extends R{constructor(e,t={}){super(e,t),this._supported=Mi.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 nu extends R{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 au={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class lu extends gs{get type(){return"PointsMaterial"}get presets(){return au}constructor(e,t={}){super(e,t),this._state=new ae({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=au[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(au).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 Au={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class cu extends gs{get type(){return"LinesMaterial"}get presets(){return Au}constructor(e,t={}){super(e,t),this._state=new ae({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=Au[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Au).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function hu(e,t,i=2){const s=t&&t.length,r=s?t[0]*i:e.length;let o=uu(e,0,r,i,!0);const n=[];if(!o||o.next===o.prev)return n;let a,l,A;if(s&&(o=function(e,t,i,s){const r=[];for(let i=0,o=t.length;i<o;i++){const n=uu(e,t[i]*s,i<o-1?t[i+1]*s:e.length,s,!1);n===n.next&&(n.steiner=!0),r.push(Bu(n))}r.sort(vu);for(let e=0;e<r.length;e++)i=bu(r[e],i);return i}(e,t,o,i)),e.length>80*i){a=1/0,l=1/0;let t=-1/0,s=-1/0;for(let o=i;o<r;o+=i){const i=e[o],r=e[o+1];i<a&&(a=i),r<l&&(l=r),i>t&&(t=i),r>s&&(s=r)}A=Math.max(t-a,s-l),A=0!==A?32767/A:0}return pu(o,n,i,a,l,A,0),n}function uu(e,t,i,s,r){let o;if(r===function(e,t,i,s){let r=0;for(let o=t,n=i-s;o<i;o+=s)r+=(e[n]-e[o])*(e[o+1]+e[n+1]),n=o;return r}(e,t,i,s)>0)for(let r=t;r<i;r+=s)o=Ru(r/s|0,e[r],e[r+1],o);else for(let r=i-s;r>=t;r-=s)o=Ru(r/s|0,e[r],e[r+1],o);return o&&Eu(o,o.next)&&(Uu(o),o=o.next),o}function du(e,t){if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!Eu(s,s.next)&&0!==Mu(s.prev,s,s.next))s=s.next;else{if(Uu(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t}function pu(e,t,i,s,r,o,n){if(!e)return;!n&&o&&function(e,t,i,s){let r=e;do{0===r.z&&(r.z=wu(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 o=null;for(t=0;r;){t++;let n=r,a=0;for(let e=0;e<i&&(a++,n=n.nextZ,n);e++);let l=i;for(;a>0||l>0&&n;)0!==a&&(0===l||!n||r.z<=n.z)?(s=r,r=r.nextZ,a--):(s=n,n=n.nextZ,l--),o?o.nextZ=s:e=s,s.prevZ=o,o=s;r=n}o.nextZ=null,i*=2}while(t>1)}(r)}(e,s,r,o);let a=e;for(;e.prev!==e.next;){const l=e.prev,A=e.next;if(o?mu(e,s,r,o):fu(e))t.push(l.i,e.i,A.i),Uu(e),e=A.next,a=A.next;else if((e=A)===a){n?1===n?pu(e=gu(du(e),t),t,i,s,r,o,2):2===n&&_u(e,t,i,s,r,o):pu(du(e),t,i,s,r,o,1);break}}}function fu(e){const t=e.prev,i=e,s=e.next;if(Mu(t,i,s)>=0)return!1;const r=t.x,o=i.x,n=s.x,a=t.y,l=i.y,A=s.y,c=Math.min(r,o,n),h=Math.min(a,l,A),u=Math.max(r,o,n),d=Math.max(a,l,A);let p=s.next;for(;p!==t;){if(p.x>=c&&p.x<=u&&p.y>=h&&p.y<=d&&xu(r,a,o,l,n,A,p.x,p.y)&&Mu(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function mu(e,t,i,s){const r=e.prev,o=e,n=e.next;if(Mu(r,o,n)>=0)return!1;const a=r.x,l=o.x,A=n.x,c=r.y,h=o.y,u=n.y,d=Math.min(a,l,A),p=Math.min(c,h,u),f=Math.max(a,l,A),m=Math.max(c,h,u),g=wu(d,p,t,i,s),_=wu(f,m,t,i,s);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=g&&b&&b.z<=_;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&xu(a,c,l,h,A,u,v.x,v.y)&&Mu(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&xu(a,c,l,h,A,u,b.x,b.y)&&Mu(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=g;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&xu(a,c,l,h,A,u,v.x,v.y)&&Mu(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=_;){if(b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&xu(a,c,l,h,A,u,b.x,b.y)&&Mu(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function gu(e,t){let i=e;do{const s=i.prev,r=i.next.next;!Eu(s,r)&&Fu(s,i,i.next,r)&&Du(s,r)&&Du(r,s)&&(t.push(s.i,i.i,r.i),Uu(i),Uu(i.next),i=e=r),i=i.next}while(i!==e);return du(i)}function _u(e,t,i,s,r,o){let n=e;do{let e=n.next.next;for(;e!==n.prev;){if(n.i!==e.i&&Cu(n,e)){let a=Su(n,e);return n=du(n,n.next),a=du(a,a.next),pu(n,t,i,s,r,o,0),void pu(a,t,i,s,r,o,0)}e=e.next}n=n.next}while(n!==e)}function vu(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 bu(e,t){const i=function(e,t){let i=t;const s=e.x,r=e.y;let o,n=-1/0;if(Eu(e,i))return i;do{if(Eu(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>n&&(n=e,o=i.x<i.next.x?i:i.next,e===s))return o}i=i.next}while(i!==t);if(!o)return null;const a=o,l=o.x,A=o.y;let c=1/0;i=o;do{if(s>=i.x&&i.x>=l&&s!==i.x&&Pu(r<A?s:n,r,l,A,r<A?n:s,r,i.x,i.y)){const t=Math.abs(r-i.y)/(s-i.x);Du(i,e)&&(t<c||t===c&&(i.x>o.x||i.x===o.x&&yu(o,i)))&&(o=i,c=t)}i=i.next}while(i!==a);return o}(e,t);if(!i)return t;const s=Su(i,e);return du(s,s.next),du(i,i.next)}function yu(e,t){return Mu(e.prev,e,t.prev)<0&&Mu(t.next,e,e.next)<0}function wu(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 Bu(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 Pu(e,t,i,s,r,o,n,a){return(r-n)*(t-a)>=(e-n)*(o-a)&&(e-n)*(s-a)>=(i-n)*(t-a)&&(i-n)*(o-a)>=(r-n)*(s-a)}function xu(e,t,i,s,r,o,n,a){return!(e===n&&t===a)&&Pu(e,t,i,s,r,o,n,a)}function Cu(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&&Fu(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Du(e,t)&&Du(t,e)&&function(e,t){let i=e,s=!1;const r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(Mu(e.prev,e,t.prev)||Mu(e,t.prev,t))||Eu(e,t)&&Mu(e.prev,e,e.next)>0&&Mu(t.prev,t,t.next)>0)}function Mu(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Eu(e,t){return e.x===t.x&&e.y===t.y}function Fu(e,t,i,s){const r=Tu(Mu(e,t,i)),o=Tu(Mu(e,t,s)),n=Tu(Mu(i,s,e)),a=Tu(Mu(i,s,t));return r!==o&&n!==a||(!(0!==r||!Iu(e,i,t))||(!(0!==o||!Iu(e,s,t))||(!(0!==n||!Iu(i,e,s))||!(0!==a||!Iu(i,t,s)))))}function Iu(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 Tu(e){return e>0?1:e<0?-1:0}function Du(e,t){return Mu(e.prev,e,e.next)<0?Mu(e,t,e.next)>=0&&Mu(e,e.prev,t)>=0:Mu(e,t,e.prev)<0||Mu(e,e.next,t)<0}function Su(e,t){const i=Lu(e.i,e.x,e.y),s=Lu(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function Ru(e,t,i,s){const r=Lu(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 Uu(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 Lu(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const ku=[0,1,0],Ou=[1,0,0],Nu=d.vec3(),Vu=d.vec3(),Qu=d.vec3(),Hu=d.vec3(),ju=d.vec3();function Gu(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 zu{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(((o,n)=>{if(!o)return;const a=s[n];if(!this._doesPlaneIntersectBoundingBox(a.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 l=this._sceneModelsData[e.id],A=l.modelOrigin;if(!l.verticesMap.has(n)){const e=a.meshes[0].isSolid(),t=[],i=[];e&&a.capMaterial&&(a.getEachVertex((e=>t.push(e[0]-A[0],e[1]-A[1],e[2]-A[2]))),a.getEachIndex((e=>i.push(e)))),l.verticesMap.set(n,t),l.indicesMap.set(n,i)}const c=l.verticesMap.get(n),h=l.indicesMap.get(n),u=-d.dotVec3(d.subVec3(t.pos,A,Nu),t.dir),p=[],f=h.length;for(let e=0;e<f;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],o=r[(e+1)%3],n=u+d.dotVec3(t.dir,s),a=u+d.dotVec3(t.dir,o);if(n*a>0)continue;const l=-n/(a-n);i.push(d.lerpVec3(l,0,1,s,o,d.vec3()))}2===i.length&&p.push(i)}p.length>0&&i.set(n,p)}));const o=new Map;i.forEach(((e,t)=>{o.set(t,[[e[0]]]),e.splice(0,1);let s=0;for(;e.length>0;){const r=o.get(t)[s][o.get(t)[s].length-1][1];let n=!1;for(let i=0;i<e.length;i++){const[a,l]=e[i];if(Gu(r,a)){o.get(t)[s].push(e[i]),e.splice(i,1),n=!0;break}if(Gu(r,l)){o.get(t)[s].push([l,a]),e.splice(i,1),n=!0;break}}if(!n&&Gu(r,o.get(t)[s][0][0])&&e.length>1)o.get(t).push([i.get(t)[0]]),e.splice(0,1),s++;else if(!n)break}}));const n=new Map;o.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)])}));n.set(i,s)}));const a=new Map;let l;n.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin;l=[];const o=i,n=[],A=new Set;for(let e=0;e<o.length;e++){if(A.has(e))continue;const t=[o[e]];A.add(e);for(let i=e+1;i<o.length;i++)A.has(i)||(this._isLoopInside(o[e],o[i])||this._isLoopInside(o[i],o[e]))&&(t.push(o[i]),A.add(i));n.push(t)}n.forEach((e=>{const i=[],s=[];let o=0;const n=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})),a=n.indexOf(Math.max(...n));e[a].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2}));for(let t=0;t<e.length;t++)t!==a&&(s.push(o/2),e[t].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2})));const A=hu(i,s),c=[];for(let e=0;e<A.length;e+=3){const s=[];for(let o=0;o<3;o++){const n=2*A[e+o],a=[i[n],i[n+1]],l=this._convertTo3D(a,t,r);s.push(l)}c.push(s)}l.push(c)})),a.set(s,l)}));const A=new Map;a.forEach(((e,t)=>{l=[],e.forEach((e=>{const t=new Map,i=[],s=[];let r=0;e.forEach((e=>{const o=[];e.forEach((e=>{const s=`${e[0].toFixed(6)},${e[1].toFixed(6)},${e[2].toFixed(6)}`;t.has(s)?o.push(t.get(s)):(i.push(e[0],e[1],e[2]),t.set(s,r),o.push(r),r++)})),s.push(...o)})),l.push({positions:i,indices:s})})),A.set(t,l)})),this._prevIntersectionModelsMap[e.id]||(this._prevIntersectionModelsMap[e.id]=new Map),d.mulVec3Scalar(t.dir,.001,ju),A.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin,o=new Array(i.size);let n=0;i.forEach(((i,a)=>{const l=i.positions,A=i.indices;l.length;const c=d.buildNormals(l,A),h=this._createUVs(l,t,r);o[n++]=new fs(this.scene,{id:`${t.id}-${s}-${a}`,geometry:new ve(this.scene,{primitive:"triangles",positions:l,indices:A,normals:c,uv:h}),origin:d.addVec3(r,ju,Nu),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(...o):this._prevIntersectionModelsMap[e.id].set(s,o)}))}))}))}_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 o=!1,n=!1;for(const e of r){const i=t.dist+d.dotVec3(t.dir,e);if(i>0&&(o=!0),i<0&&(n=!0),o&&n)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 fs(this.scene,{clippable:!1,geometry:new ve(this.scene,Oe({startPoint:e[0],endPoint:e[1]})),material:new bs(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),o=d.normalizeVec3(r);return[d.dotVec3(e,i),d.dotVec3(e,o)]}_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 o=t[e][0][0],n=t[e][0][1],a=t[r][0][0],l=t[r][0][1];n>i[1]!=l>i[1]&&i[0]<(a-o)*(i[1]-n)/(l-n)+o&&(s=!s)}return s}_convertTo3D(e,t,i){let s,r=t.dir,o=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 n=d.vec3(r),a=d.cross3Vec3(n,s),l=d.normalizeVec3(a),A=e[0],c=e[1],h=[s[0]*A+l[0]*c,s[1]*A+l[1]*c,s[2]*A+l[2]*c],u=d.dotVec3(r,[o[0]-h[0]-i[0],o[1]-h[1]-i[1],o[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=Nu;r.set(t.dir),d.normalizeVec3(r);const o=Vu,n=[];for(let t=0;t<e.length;t+=3){o[0]=e[t]+i[0],o[1]=e[t+1]+i[1],o[2]=e[t+2]+i[2];const a=d.subVec3(o,s,Qu),l=d.dotVec3(a,r);d.subVec3(o,d.mulVec3Scalar(r,l,Qu),o);const A=Math.abs(d.dotVec3(r,ku))<.999?d.cross3Vec3(r,ku,Qu):Ou,c=d.cross3Vec3(r,A,Qu);d.normalizeVec3(c,c);const h=d.subVec3(o,s,o);n.push(d.dotVec3(h,d.normalizeVec3(d.cross3Vec3(c,r,Hu))),d.dotVec3(h,c))}return n}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 Wu(e,t){const i={};let s,r;for(let o=0,n=t.length;o<n;o++)s=t[o],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 Xu extends R{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 gh(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}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Rh(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 Uh(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new ru(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new ou(this,{enabled:t.saoEnabled}),this.crossSections=new nu(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 Lh(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new iu(this,{id:"default.camera",dontClear:!0}),this._sectionCaps=new zu(this),new Uc(this,{color:[1,1,1],intensity:.7}),new kc(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new kc(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 "+y.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],y.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}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}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())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;r<i;r++)t.pass=r,this.fire("rendering",t,!0),o=s||0===r,this._renderer.render({pass:r,clear:o,force:e}),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:(!y.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:(!y.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:(!y.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"]||Ce(ve)}get material(){return this.components["default.material"]||new bs(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new Gs(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 Gs(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 Gs(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 Ws(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 lu(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 cu(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,o=d.MIN_DOUBLE,n=d.MIN_DOUBLE;const a=this._collidables;let l,A=!1;for(const c in a)if(a.hasOwnProperty(c)){if(l=a[c],!1===l.collidable)continue;e=l.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]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){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=Wu(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=Wu(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){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}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(y.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,o=d.MIN_DOUBLE,n=d.MIN_DOUBLE,a=d.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const l=e.aabb;l[0]<i&&(i=l[0]),l[1]<s&&(s=l[1]),l[2]<r&&(r=l[2]),l[3]>o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,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){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s<r;s++){const r=e[s];let o=this.objects[r];if(o)i=t(o)||i;else{const e=this.modelIds;for(let s=0,n=e.length;s<n;s++){const n=e[s],a=d.globalizeObjectId(n,r);o=this.objects[a],o&&(i=t(o)||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 o=function(...e){i=e,r++},n=this.on("tick",(()=>{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();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 Ku=d.vec4(),Zu=d.vec4(),Ju=d.vec3(),Yu=d.vec3(),qu=d.vec3(),$u=d.vec4(),ed=d.vec4(),td=d.vec4();class id{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,Ju);s=d.lenVec3(t)<i}if("perspective"===r.projection){r.ortho.scale=r.ortho.scale-i;const s=this._unproject(t,$u),o=d.subVec3(s,r.eye,td),n=d.mulVec3Scalar(d.normalizeVec3(o),-i,[]);if(r.eye=[r.eye[0]-n[0],r.eye[1]-n[1],r.eye[2]-n[2]],r.look=[r.look[0]-n[0],r.look[1]-n[1],r.look[2]-n[2]],e){const t=d.subVec3(e,r.eye,Ju),i=d.lenVec3(t),s=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,Yu)),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,$u);r.ortho.scale=r.ortho.scale-i,r.ortho._update();const s=this._unproject(t,ed),o=d.subVec3(s,e,td),n=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,Ju)),-i,Yu),a=d.addVec3(o,n,qu);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]]}return s}_unproject(e,t){const i=this._scene.camera,s=i.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o);return i.project.unproject(e,a,Ku,Zu,t),t}destroy(){}}const sd=d.vec3(),rd=d.vec3(),od=d.vec3(),nd=d.vec4(),ad=d.vec4(),ld=d.vec4(),Ad=Math.PI-.001;class cd{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),qe(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new we(this._scene,De({radius:s})),this._pivotSphere=new fs(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 o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(qe(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 bs(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,sd)),i=d.cross3Vec3(t,e.worldUp,rd);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),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=nd;t.project.unproject(e,a,ad,ld,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,sd)),c=d.addVec3(t.eye,d.mulVec3Scalar(A,i,rd),od);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 o=r<0,n=r>0,a=Math.abs(this._polar-.001)<.005,l=Math.abs(this._polar-Ad)<.005;let A=this._polar+.01*r;A=a&&o?.001:l&&n?Ad:d.clamp(A,.001,Ad),this._polar=A;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 p=d.lookAtMat4v(c,u,i.worldUp);p=d.inverseMat4(p);const f=d.transformVec3(p,this._cameraOffset);p[12]-=f[0],p[13]-=f[1],p[14]-=f[2];const m=[p[8],p[9],p[10]];i.eye=[p[12],p[13],p[14]],d.subVec3(i.eye,d.mulVec3Scalar(m,h),i.look),i.up=[p[4],p[5],p[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 hd{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 uh;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 ud=d.vec2();class dd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a,l,A,c=0,h=0,u=0,p=0,f=!1;const m=d.vec3();let g=!0;const _=this._scene.canvas.canvas,v=[];function b(e=!0){c=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],p=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(f=!0,m.set(o.pickResult.worldPos)):f=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!1}),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{v.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{v.splice(0)}),_.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:v[e.input.KEY_SHIFT]||i.planView?(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b()):(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b(!1));break;case 2:l=!0,v[e.input.MOUSE_MIDDLE_BUTTON]=!0,b();break;case 3:A=!0,v[e.input.MOUSE_RIGHT_BUTTON]=!0,i.panRightClick&&b()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!a&&!l&&!A)return;const o=e.canvas.boundary,u=o[2],p=o[3],g=s.pointerCanvasPos[0],_=s.pointerCanvasPos[1],b=i.planView||n._isKeyDownForAction(n.MOUSE_PAN,v),y=n._isKeyDownForAction(n.MOUSE_ROTATE,v),w=document.pointerLockElement?t.movementX:g-c,B=document.pointerLockElement?t.movementY:_-h;if(b){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(f?d.lenVec3(d.subVec3(m,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*w*i/p,r.panDeltaY+=1.5*B*i/p}else r.panDeltaX+=.5*t.ortho.scale*(w/p),r.panDeltaY+=.5*t.ortho.scale*(B/p)}else y&&(i.planView||(i.firstPerson?(r.rotateDeltaY-=w/u*i.dragRotationRate/2,r.rotateDeltaX+=B/p*(i.dragRotationRate/4)):(r.rotateDeltaY-=w/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=B/p*(1.5*i.dragRotationRate))));c=g,h=_}),_.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:case 2:case 3:a=!1,l=!1,A=!1,v[e.input.MOUSE_LEFT_BUTTON]=!1,v[e.input.MOUSE_MIDDLE_BUTTON]=!1,v[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,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,ud);const i=ud[0],s=ud[1];Math.abs(i-u)<3&&Math.abs(s-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:ud,event:e},!0)}_.style.removeProperty("cursor")}}),_.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const y=1/60;let w=null;_.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel&&n._isKeyDownForAction(n.MOUSE_DOLLY,v)))return;const t=performance.now()/1e3;var o=null!==w?t-w:0;w=t,o>.05&&(o=.05),o<y&&(o=y);const a=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===a)return;const l=a/Math.abs(a);r.dollyDelta+=-l*o*i.mouseWheelDollyRate,g&&(s.followPointerDirty=!0,g=!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 pd=d.vec3(),fd=d.vec3(),md=d.vec3(),gd=d.vec3(),_d=d.vec3(),vd={eye:d.vec3(),look:d.vec3(),up:d.vec3()};class bd{constructor(e,t,i,s){this._scene=e;const r=t.cameraControl,o=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),h=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||c||h))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,pd);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),m=1.1*p;vd.orthoScale=m,n?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldRight,f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):a?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldForward,f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):l?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldRight,-f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):A?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldForward,-f,fd),_d)),vd.look.set(pd),vd.up.set(o.worldUp)):c?(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldUp,f,fd),_d)),vd.look.set(pd),vd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,md),gd))):h&&(vd.eye.set(d.addVec3(pd,d.mulVec3Scalar(o.worldUp,-f,fd),_d)),vd.look.set(pd),vd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,md)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(pd),t.cameraFlight.duration>0?t.cameraFlight.flyTo(vd,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(vd),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class yd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;let l=!1,A=!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(l||A)return;if(a.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),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),h=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||h||u||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});c.addEventListener("mousemove",u),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!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&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot(),this._lastClickedWorldPos=t.worldPos.slice()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):this._lastClickedWorldPos?n.setPivotPos(this._lastClickedWorldPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||c)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(h(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.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 wd{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[];e.canvas.canvas;let a=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{a=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,t.pivotController.getPivoting()&&t.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{n.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{n.splice(0)}),this._onTick=e.on("tick",(l=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,c=l.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=c*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),a&&(s.followPointerDirty=!0,a=!1)}}const h=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),m=A._isKeyDownForAction(A.PAN_DOWN,n),g=(n[o.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(h||u||d||p||f||m)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=g:f&&(r.panDeltaY+=-g),p?r.panDeltaX+=-g:d&&(r.panDeltaX+=g),u?r.panDeltaZ+=g:h&&(r.panDeltaZ+=-g))}))}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 Bd=d.vec3();class Pd{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController,A=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&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(d.lenVec3(d.subVec3(u,e.camera.eye,Bd)));h=t/i.dollyProximityThreshold}h<i.dollyMinSpeed&&(h=i.dollyMinSpeed)}}else h=1,u=null;const p=r.dollyDelta*h;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(!i.firstPerson&&i.followPointer&&a.getPivoting()?(a.continuePivot(r.rotateDeltaY,r.rotateDeltaX),a.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?o.pitch(-r.rotateDeltaX):o.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?o.yaw(r.rotateDeltaY):o.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,t=A._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,n;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){o.xUp?(s=o.eye[0],n=o.look[0]):o.yUp?(s=o.eye[1],n=o.look[1]):o.zUp&&(s=o.eye[2],n=o.look[2]),o.pan(e);const t=o.eye,i=o.look;o.xUp?(t[0]=s,i[0]=n):o.yUp?(t[1]=s,i[1]=n):o.zUp&&(t[2]=s,i[2]=n),o.eye=t,o.look=i}else o.pan(e);t=A._cursors.pan}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==p){if(t=p<0?A._cursors.dollyForward:A._cursors.dollyBackward,i.firstPerson){let e,t;if(i.constrainVertical&&(o.xUp?(e=o.eye[0],t=o.look[0]):o.yUp?(e=o.eye[1],t=o.look[1]):o.zUp&&(e=o.eye[2],t=o.look[2])),i.followPointer){l.dollyToCanvasPos(u,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.pan([0,0,p]),o.ortho.scale=o.ortho.scale-p;if(i.constrainVertical){const i=o.eye,s=o.look;o.xUp?(i[0]=e,s[0]=t):o.yUp?(i[1]=e,s[1]=t):o.zUp&&(i[2]=e,s[2]=t),o.eye=i,o.look=s}}else if(i.planView)if(i.followPointer){l.dollyToCanvasPos(u,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);else if(i.followPointer){l.dollyToCanvasPos(u,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);r.dollyDelta*=i.dollyInertia}n.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class xd{constructor(e,t,i,s,r){this._scene=e;const o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Cd(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Cd(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.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 Cd(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 Md=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 Ed{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),c=d.vec2(),h=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Md(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));h.length<r.length;)h.push(d.vec2());for(let e=0,t=r.length;e<t;++e)Md(r[e],h[e]);p=r.length}),u.addEventListener("touchend",this._canvasTouchEndHandler=()=>{n.getPivoting()&&(n.endPivot(),n.hidePivot())}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],m=t.touches;if(t.touches.length===p){if(1===p){Md(m[0],l),d.subVec2(l,h[0],c);const t=c[0],o=c[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=m[0],n=m[1];Md(t,l),Md(n,A);const a=d.geometricMeanVec2(h[0],h[1]),c=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,c,p);const f=p[0],g=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(h[0],h[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.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-=f*s/u*i.touchPanRate,r.panDeltaY-=g*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(g/u)*i.touchPanRate;s.pointerCanvasPos=c}for(let e=0;e<p;++e)Md(m[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 Fd=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 Id{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a;const l=[],A=new Float32Array(2);let c=-1,h=-1;const u=this._scene.canvas.canvas,p=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,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,Fd(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,h=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{i.active&&i.pointerEnabled&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(h)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else c=-1;for(;l.length<r.length;)l.push(new Float32Array(2));for(let e=0,t=r.length;e<t;++e)Fd(r[e],l[e]);l.length=r.length},{passive:!0}),u.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(h>-1&&c-h<325?(Fd(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),h=-1):d.distVec2(l[0],A)<4&&(Fd(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),h=t),c=-1),l.length=r.length;for(let e=0,t=r.length;e<t;++e)l[e][0]=r[e].pageX,l[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 Td extends R{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 hd(this,this._configs),pivotController:new cd(i,this._configs),panController:new id(i),cameraFlight:new se(this,{duration:.5})},this._handlers=[new xd(this.scene,this._controllers,this._configs,this._states,this._updates),new Ed(this.scene,this._controllers,this._configs,this._states,this._updates),new dd(this.scene,this._controllers,this._configs,this._states,this._updates),new bd(this.scene,this._controllers,this._configs,this._states,this._updates),new yd(this.scene,this._controllers,this._configs,this._states,this._updates),new Id(this.scene,this._controllers,this._configs,this._states,this._updates),new wd(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 Pd(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",y.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 Dd{constructor(e,t,i,s,r){this.name=e,this.type=i,this.value=t,this.valueType=s,this.description=r}}class Sd{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 Dd(i.name,i.value,i.type,i.valueType,i.description))}}}}class Rd{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,o=s.length;r<o;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,o=s.length;r<o;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 o=0,n=s.length;o<n;o++)e(s[o])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class Ud{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 Sd({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 o=i.metaObjects[r];if(!o){const e=s.type,t=s.originalSystemId,i=s.propertySets||s.propertySetIds;o=new Rd({id:r,originalSystemId:t,parentId:s.parent,type:e,name:s.name,attributes:s.attributes,propertySetIds:i,external:s.external}),this.metaScene.metaObjects[r]=o,o.metaModels=[]}this.metaObjects[r]=o,s.parent||(this.rootMetaObjects.push(o),i.rootMetaObjects[r]=o),o.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 o=e[r];o?t[s]=o: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 Ld{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 Ud({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],o=t&&t.length>0?kd(t):null,n=i&&i.length>0?kd(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r<l;r++)a(i[r])};return a(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function kd(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>
|