From e25222acc33e4d841effe686868119dd6497684a Mon Sep 17 00:00:00 2001 From: lindsay Date: Tue, 12 Dec 2023 13:11:34 +0100 Subject: [PATCH] npm bump, rebuild --- dist/xeokit-bim-viewer.es.js | 6 ------ dist/xeokit-bim-viewer.min.es.js | 2 +- dist/xeokit-bim-viewer.min.umd.js | 2 +- dist/xeokit-bim-viewer.umd.js | 6 ------ package-lock.json | 18 +++++++++--------- package.json | 4 ++-- 6 files changed, 13 insertions(+), 25 deletions(-) diff --git a/dist/xeokit-bim-viewer.es.js b/dist/xeokit-bim-viewer.es.js index 3298a216..a34f6654 100644 --- a/dist/xeokit-bim-viewer.es.js +++ b/dist/xeokit-bim-viewer.es.js @@ -51942,12 +51942,6 @@ class TrianglesBatchingLayer { this._state.origin.set(cfg.origin); } - /** - * The axis-aligned World-space boundary of this TrianglesBatchingLayer's positions. - * @type {*|Float64Array} - */ - this.aabb = math.collapseAABB3(); - /** * When true, this layer contains solid triangle meshes, otherwise this layer contains surface triangle meshes * @type {boolean} diff --git a/dist/xeokit-bim-viewer.min.es.js b/dist/xeokit-bim-viewer.min.es.js index 54db2b73..7cd00e02 100644 --- a/dist/xeokit-bim-viewer.min.es.js +++ b/dist/xeokit-bim-viewer.min.es.js @@ -1,4 +1,4 @@ -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 s{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class i{constructor(){this.items=[]}}class r{constructor(e,t,s,i,r){this.id=e,this.getTitle=t,this.doAction=s,this.getEnabled=i,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._eventSubs={},!1!==e.hideOnMouseDown&&(document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const o=this._getNextId(),n=new s(o);for(let s=0,o=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new r(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(i);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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("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;ewindow.innerHeight&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}let n=!0,a=n?Float64Array:Float32Array;const l=new a(3),h=new a(16),c=new a(16),A=new a(4),u={setDoublePrecisionEnabled(e){n=e,a=n?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>n,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new a(e||2),vec3:e=>new a(e||3),vec4:e=>new a(e||4),mat3:e=>new a(e||9),mat3ToMat4:(e,t=new a(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new a(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const i=new a(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new a(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>u.dotVec4(e,e),lenVec4:e=>Math.sqrt(u.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=>u.dotVec3(e,e),sqLenVec2:e=>u.dotVec2(e,e),lenVec3:e=>Math.sqrt(u.sqLenVec3(e)),distVec3:(()=>{const e=new a(3);return(t,s)=>u.lenVec3(u.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(u.sqLenVec2(e)),distVec2:(()=>{const e=new a(2);return(t,s)=>u.lenVec2(u.subVec2(t,s,e))})(),rcpVec3:(e,t)=>u.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/u.lenVec4(e);return u.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/u.lenVec3(e);return u.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/u.lenVec2(e);return u.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=u.dotVec3(e,t)/Math.sqrt(u.sqLenVec3(e)*u.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new a(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=u.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=u.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=u.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||u.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:()=>u.m4s(0),setMat4ToOnes:()=>u.m4s(1),diagonalMat4v:e=>new a([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,i)=>u.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>u.diagonalMat4c(e,e,e,e),identityMat4:(e=new a(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new a(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>u.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],y=e[14],E=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],b=t[7],D=t[8],N=t[9],C=t[10],O=t[11],S=t[12],x=t[13],w=t[14],M=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*y,s[3]=g*n+v*c+I*d+_*E,s[4]=T*i+R*a+P*A+b*f,s[5]=T*r+R*l+P*u+b*m,s[6]=T*o+R*h+P*p+b*y,s[7]=T*n+R*c+P*d+b*E,s[8]=D*i+N*a+C*A+O*f,s[9]=D*r+N*l+C*u+O*m,s[10]=D*o+N*h+C*p+O*y,s[11]=D*n+N*c+C*d+O*E,s[12]=S*i+x*a+w*A+M*f,s[13]=S*r+x*l+w*u+M*m,s[14]=S*o+x*h+w*p+M*y,s[15]=S*n+x*c+w*d+M*E,s},mulMat3(e,t,s){s||(s=new a(9));const i=e[0],r=e[3],o=e[6],n=e[1],l=e[4],h=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],y=t[4],E=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*y+o*v,s[6]=i*f+r*E+o*I,s[1]=n*p+l*m+h*g,s[4]=n*d+l*y+h*v,s[7]=n*f+l*E+h*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*y+u*v,s[8]=c*f+A*E+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=u.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],y=e[15],E=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,b=c*y-p*d,D=A*m-u*f,N=A*y-p*f,C=u*y-p*m,O=1/(E*C-g*N+v*D+I*b-_*P+T*R);return t[0]=(a*C-l*N+h*D)*O,t[1]=(-i*C+r*N-o*D)*O,t[2]=(f*T-m*_+y*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*C+l*b-h*P)*O,t[5]=(s*C-r*b+o*P)*O,t[6]=(-d*T+m*v-y*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*N-a*b+h*R)*O,t[9]=(-s*N+i*b-o*R)*O,t[10]=(d*_-f*v+y*E)*O,t[11]=(-c*_+A*v-p*E)*O,t[12]=(-n*D+a*P-l*R)*O,t[13]=(s*D-i*P+r*R)*O,t[14]=(-d*I+f*g-m*E)*O,t[15]=(c*I-A*g+u*E)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||u.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||u.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new a(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.translationMat4v(e,r))})(),translationMat4s:(e,t)=>u.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>u.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=u.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,p,d,f,m;return c=a*l,A=l*h,p=h*a,d=a*r,f=l*r,m=h*r,(s=s||u.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*p-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*p+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>u.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=u.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=u.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new a(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>u.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=u.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,p=i*h,d=r*l,f=r*h,m=o*h,y=n*a,E=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=p-E,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+y,s[7]=0,s[8]=p+E,s[9]=f-y,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=u.vec4()){const i=u.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],p=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,p),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,p),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,p),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,p),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,p))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,p),s[1]=0)),s},composeMat4:(e,t,s,i=u.mat4())=>(u.quaternionToRotationMat4(t,i),u.scaleMat4v(s,i),u.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new a(3),t=new a(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=u.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=u.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=u.lenVec3(e);u.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,u.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=u.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],p=t[2];if(r===c&&o===A&&n===p)return u.identityMat4();let d,f,m,y,E,g,v,I,_,T;return d=r-c,f=o-A,m=n-p,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,y=l*m-h*f,E=h*d-a*m,g=a*f-l*d,T=Math.sqrt(y*y+E*E+g*g),T?(T=1/T,y*=T,E*=T,g*=T):(y=0,E=0,g=0),v=f*g-m*E,I=m*y-d*g,_=d*E-f*y,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=y,i[1]=v,i[2]=d,i[3]=0,i[4]=E,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(y*r+E*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>u.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=u.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];u.addVec4(r,i,h),u.subVec4(r,i,c);const o=2*i[2],n=c[0],a=c[1],l=c[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=h[0]/n,s[9]=h[1]/a,s[10]=-h[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],u.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,s=u.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=u.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],y=e[8],E=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new a(16),t=new a(16),s=new a(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||u.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||u.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=u.vec4()){const i=e[0]*u.DEGTORAD/2,r=e[1]*u.DEGTORAD/2,o=e[2]*u.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=u.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const p=s+n+c;return p>0?(A=.5/Math.sqrt(p+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=u.vec4()){const i=Math.sqrt(u.dotVec3(e,e)*u.dotVec3(t,t));let r=i+u.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):u.cross3Vec3(e,t,s),s[3]=r,u.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=u.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new a(16);return(t,s,i)=>(i=i||u.vec3(),u.quaternionToRotationMat4(t,e),u.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=u.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=u.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,p=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-p*-a,s[1]=A*h+d*-a+p*-n-c*-l,s[2]=p*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=u.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,p=n*s,d=a*s,f=l*s,m=a*i,y=l*i,E=l*r;return t[0]=1-(m+E),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(p+E),t[6]=y+h,t[8]=f+c,t[9]=y-h,t[10]=1-(p+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,y=o*l;return t[0]=1-(u+d),t[4]=c-y,t[8]=A+m,t[1]=c+y,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+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 s=u.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,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)=>u.normalizeQuaternion(u.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=u.vec4()){const s=(e=u.normalizeQuaternion(e,A))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,t},AABB3:e=>new a(e||6),AABB2:e=>new a(e||4),OBB3:e=>new a(e||32),OBB2:e=>new a(e||16),Sphere3:(e,t,s,i)=>new a([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],y=e[9],E=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new a(3),t=new a(3),s=new a(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],u.subVec3(t,e,s),Math.abs(u.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new a(3),t=new a(3),s=new a(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=u.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(u.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||u.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||u.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=u.AABB3())=>(e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MAX_DOUBLE,e[3]=u.MIN_DOUBLE,e[4]=u.MIN_DOUBLE,e[5]=u.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=u.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new a(3);return(t,s,i)=>{s=s||u.AABB3();let r,o,n,a=u.MAX_DOUBLE,l=u.MAX_DOUBLE,h=u.MAX_DOUBLE,c=u.MIN_DOUBLE,A=u.MIN_DOUBLE,p=u.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>p&&(p=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=p,s}})(),OBB3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new a(3);return(t,s)=>{s=s||u.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=u.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=u.vec3()){let s=0,i=0,r=0;for(var o=0,n=e.length;o(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](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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MIN_DOUBLE,e[3]=u.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=u.AABB2()){let s,i,r,o,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=u.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,p=r*l-o*a,d=Math.sqrt(c*c+A*A+p*p);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=p/d),i},rayTriangleIntersect:(()=>{const e=new a(3),t=new a(3),s=new a(3),i=new a(3),r=new a(3);return(o,n,a,l,h,c)=>{c=c||u.vec3();const A=u.subVec3(l,a,e),p=u.subVec3(h,a,t),d=u.cross3Vec3(n,p,s),f=u.dotVec3(A,d);if(f<1e-6)return null;const m=u.subVec3(o,a,i),y=u.dotVec3(m,d);if(y<0||y>f)return null;const E=u.cross3Vec3(m,A,r),g=u.dotVec3(n,E);if(g<0||y+g>f)return null;const v=u.dotVec3(p,E)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new a(3),t=new a(3),s=new a(3),i=new a(3);return(r,o,n,a,l,h)=>{h=h||u.vec3(),o=u.normalizeVec3(o,e);const c=u.subVec3(a,n,t),A=u.subVec3(l,n,s),p=u.cross3Vec3(c,A,i);u.normalizeVec3(p,p);const d=-u.dotVec3(n,p),f=-(u.dotVec3(r,p)+d)/u.dotVec3(o,p);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new a(3),t=new a(3),s=new a(3);return(i,r,o,n,a)=>{const l=u.subVec3(n,r,e),h=u.subVec3(o,r,t),c=u.subVec3(i,r,s),A=u.dotVec3(l,l),p=u.dotVec3(l,h),d=u.dotVec3(l,c),f=u.dotVec3(h,h),m=u.dotVec3(h,c),y=A*f-p*p;if(0===y)return null;const E=1/y,g=(f*d-p*m)*E,v=(A*m-p*d)*E;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=u.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,y=0;for(f=0,m=e.length;f{const e=new a(3),t=new a(3),s=new a(3),i=new a(3),r=new a(3),o=new a(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let p,d,f,m,y,E,g;for(h=0,c=a.length;h{const e=new a(3),t=new a(3),s=new a(3),i=new a(3),r=new a(3),o=new a(3),n=new a(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const p=1e4;let d,f,m,y,E,g;for(f=0,y=e.length;f{const e=new a(4),t=new a(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,u.transformVec4(s,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],u.transformVec3(s,e,t),u.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new a(16),t=new a(16),s=new a(4),i=new a(4),r=new a(4),o=new a(4);return(n,a,l,h,c,A)=>{const p=u.mulMat4(l,a,e),d=u.inverseMat4(p,t),f=n.width,m=n.height,y=(h[0]-f/2)/(f/2),E=-(h[1]-m/2)/(m/2);s[0]=y,s[1]=E,s[2]=-1,s[3]=1,u.transformVec4(d,s,i),u.mulVec4Scalar(i,1/i[3]),r[0]=y,r[1]=E,r[2]=1,r[3]=1,u.transformVec4(d,r,o),u.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],u.subVec3(o,i,A),u.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new a(3),t=new a(3);return(s,i,r,o,n,a,l)=>{u.canvasPosToWorldRay(s,i,r,n,e,t),u.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new a(16),t=new a(4),s=new a(4);return(i,r,o,n,a)=>{const l=u.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],u.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new a(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let h,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,h=0,c=s.length;hn[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(s.length<20||o>10)return l.triangles=s,l.leaf=!0,l;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),l.splitDim=u;const p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let y=0;for(h=0,c=s.length;h{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};u.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}(),u.planeClipsPositions3=function(e,t,s,i=3){for(let r=0,o=s.length;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;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),s=new Uint8Array(e);for(var n=0;n=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}},I={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},_=[];let T,R=0,P=0;const b=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(b.scenes[e.id])return void console.error(`[ERROR] Scene ${y.inQuotes(e.id)} already exists`)}else e.id=g.addItem({});b.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;E[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},p.components.scenes++,e.once("destroyed",(()=>{g.removeItem(e.id),delete b.scenes[e.id],delete E[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in b.scenes)b.scenes.hasOwnProperty(t)&&(e=b.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete b.scenes[e.id]))},this.scheduleTask=function(e,t){v.push(e),v.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;v.length>0&&(e<0||i0&&T>0){var t=1e3/T;P+=t,_.push(t),_.length>=30&&(P-=_.shift()),p.frame.fps=Math.round(P/_.length)}!function(e){const t=b.runTasks(e+10),s=b.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=s,p.frame.tasksBudget=10}(e),function(e){for(var t in I.time=e,b.scenes)if(b.scenes.hasOwnProperty(t)){var s=b.scenes[t];I.sceneId=t,I.startTime=s.startTime,I.deltaTime=null!=I.prevTime?I.time-I.prevTime:0,s.fire("tick",I,!0)}I.prevTime=e}(e),function(){const e=b.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=E[n],i||(i=E[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),R=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(D)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(D);class N{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 N))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,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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 s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(y.isNumeric(s)||y.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+y.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+y.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+y.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():b.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_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,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class w{constructor(){this.planes=[new x,new x,new x,new x,new x,new x]}}function M(e,t,s){const i=u.mulMat4(s,t,S),r=i[0],o=i[1],n=i[2],a=i[3],l=i[4],h=i[5],c=i[6],A=i[7],p=i[8],d=i[9],f=i[10],m=i[11],y=i[12],E=i[13],g=i[14],v=i[15];e.planes[0].set(a-r,A-l,m-p,v-y),e.planes[1].set(a+r,A+l,m+p,v+y),e.planes[2].set(a-o,A-h,m-d,v-E),e.planes[3].set(a+o,A+h,m+d,v+E),e.planes[4].set(a-n,A-c,m-f,v-g),e.planes[5].set(a+n,A+c,m+f,v+g)}function B(e,t){let s=w.INSIDE;const i=C,r=O;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return w.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=w.INTERSECT)}return s}w.INSIDE=0,w.INTERSECT=1,w.OUTSIDE=2;class F extends N{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=u.vec2(),this._canvasMarqueeCorner2=u.vec2(),this._canvasMarquee=u.AABB2(),this._marqueeFrustum=new w,this._marqueeFrustumProjMat=u.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!==F.PICK_MODE_INSIDE&&e!==F.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===F.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=(s,i=w.INTERSECT)=>{if(i===w.INTERSECT&&(i=B(this._marqueeFrustum,s.aabb)),i!==w.OUTSIDE){if(s.entities){const t=s.entities;for(let s=0,i=t.length;s3||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,s=e.clientHeight,i=e.clientLeft,r=e.clientTop,o=2/t,n=2/s,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-i)*o-1,h=(this._canvasMarquee[2]-i)*o-1,c=-(this._canvasMarquee[3]-r)*n+1,A=-(this._canvasMarquee[1]-r)*n+1,p=this.viewer.scene.camera.frustum.near*(17*a);u.frustumMat4(l,h,c*a,A*a,p,1e4,this._marqueeFrustumProjMat),M(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)}}F.PICK_MODE_INTERSECTS=0,F.PICK_MODE_INSIDE=1;class L{constructor(e,t,s){this.id=s&&s.id?s.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)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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)}}const U=u.vec3(),H=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(i,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(i,t,s),u.setMat4Translation(i,s,o),o.slice()}}();function G(e,t,s){const i=Float32Array.from([e[0]])[0],r=e[0]-i,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=i,t[1]=o,t[2]=a,s[0]=r,s[1]=n,s[2]=l}function k(e,t,s,i=1e3){const r=u.getPositionsCenter(e,U),o=Math.round(r[0]/i)*i,n=Math.round(r[1]/i)*i,a=Math.round(r[2]/i)*i;s[0]=o,s[1]=n,s[2]=a;const l=0!==s[0]||0!==s[1]||0!==s[2];if(l)for(let s=0,i=e.length;s0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(u.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){te.set(this._viewPos),te[3]=1,u.transformPoint4(this.scene.camera.projMatrix,te,se);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+se[0]/se[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-se[1]/se[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){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof ee?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)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),G(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._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class re{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class oe{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!0,this._culled=!1;var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ne{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var ae=u.vec3(),le=u.vec3();class he extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._cornerMarker=new ie(s,t.corner),this._targetMarker=new ie(s,t.target),this._originWorld=u.vec3(),this._cornerWorld=u.vec3(),this._targetWorld=u.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new re(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new re(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new ne(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(u.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const p=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>p||f>p||m>p)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const y=this._container.getBoundingClientRect();for(var r=i.top-y.top,o=i.left-y.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const s=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),h.set(s),this._mouseState){case 0:this.markerDiv.style.marginLeft=s[0]-5+"px",this.markerDiv.style.marginTop=s[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,i&&(i.visible=!0,i.pointerPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class ue extends L{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new Ae(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.corner,i=e.target,r=new he(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t
',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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.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 s=this._element;s&&(s.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 de=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class fe extends N{constructor(e,t={}){super(e,t),this._backgroundColor=u.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 s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new pe(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-"+u.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?ye.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?ye.FS_MAX_FLOAT_PRECISION="mediump":ye.FS_MAX_FLOAT_PRECISION="lowp":ye.FS_MAX_FLOAT_PRECISION="mediump",ye.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),ye.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),ye.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),ye.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),ye.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ye.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),ye.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),ye.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),ye.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),ye.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){ye.SUPPORTED_EXTENSIONS[e]=!0})))}class ge{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}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}}class ve{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function Pe(e){console.error(e.join("\n"))}class be{constructor(e,t){this.id=Te.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 ve(e,e.VERTEX_SHADER,Re(this.source.vertex)),this._fragmentShader=new ve(e,e.FRAGMENT_SHADER,Re(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Pe(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Pe(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Pe(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Pe(this.errors);let t,s,i,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 Pe(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ne{constructor(e,t){this.scene=e,this.aabb=u.AABB3(),this.origin=u.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-t){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{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 s=this._occlusionLayers[t];s||(s=new Ne(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ne(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.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;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new be(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),p=Math.random(),d="perspective"===i.camera.projection;xe[0]=o,xe[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,xe),t.uniform1f(this._uRandomSeed,p);const f=e.getDepthTexture();s.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)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new be(s,{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 i=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 De(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new De(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new De(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.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 Me=new Float32Array(Ge(17,[0,1])),Be=new Float32Array(Ge(17,[1,0])),Fe=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(He(i,t));return s}(17,4)),Le=new Float32Array(2);class Ue{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 be(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]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new De(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new De(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new De(e,e.ELEMENT_ARRAY_BUFFER,i,i.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,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Le[0]=n,Le[1]=a,i.uniform2fv(this._uViewport,Le),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Be):i.uniform2fv(this._uSampleOffsets,Me),i.uniform1fv(this._uSampleWeights,Fe);const A=e.getDepthTexture(),p=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,p,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function He(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Ge(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class ke{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.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,s=null){const i=this.gl,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),s?i.texStorage2D(i.TEXTURE_2D,1,s,e,t):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),r}_touch(...e){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;this.buffer.textures.forEach((e=>i.deleteTexture(e))),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,s,e)))):r.push(this.createTexture(t,s)),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();i.bindFramebuffer(i.FRAMEBUFFER,a);for(let e=0;e0&&i.drawBuffers(r.map(((e,t)=>i.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.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:s},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,s=null,i=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,h=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,s||c.RGBA,i||c.UNSIGNED_BYTE,h,0),h}readArray(e=null,t=null,s=Uint8Array,i=4,r=0){const o=new s(this.buffer.width*this.buffer.height*i),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(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;ee.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 Ve{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let i=s[e];return i||(i=new ke(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=i),i}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function je(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=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":s=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":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}const Qe=function(t,s){s=s||{};const i=new me(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!s.transparent,a=s.alphaDepthMask,l=new e({});let h={},c={},A=!0,d=!0,f=!0,m=!0,y=!0,E=!0,g=!0,v=!0;const I=new Ve(t);let _=!1;const T=new we(t),R=new Ue(t);function P(){A&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableMap,i=t.drawableListPreCull;let r=0;for(let e in s)s.hasOwnProperty(e)&&(i[r++]=s[e]);i.length=r}}(),A=!1,d=!0),d&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),d=!1,f=!0),f&&function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableListPreCull,i=t.drawableList;let r=0;for(let e=0,t=s.length;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=p.size[0],i=t%s-Math.floor(s/2),r=Math.floor(t/s)-Math.floor(s/2),o=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));D.push({x:i,y:r,dist:o,isVertex:n&&a?E[e+3]>y.length/2:n,result:[E[e+0],E[e+1],E[e+2],E[e+3]],normal:[g[e+0],g[e+1],g[e+2],g[e+3]],id:[v[e+0],v[e+1],v[e+2],v[e+3]]})}let S=null,x=null,w=null,M=null;if(D.length>0){D.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),M=D[0].isVertex?"vertex":"edge";const e=D[0].result,t=D[0].normal,s=D[0].id,i=y[e[3]],r=i.origin,o=i.coordinateScale;x=u.normalizeVec3([t[0]/u.MAX_INT,t[1]/u.MAX_INT,t[2]/u.MAX_INT]),S=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],w=l.items[s[0]+(s[1]<<8)+(s[2]<<16)+(s[3]<<24)]}if(null===_&&null==S)return null;let B=null;null!==S&&(B=t.camera.projectWorldPos(S));const F=w&&w.delegatePickedEntity?w.delegatePickedEntity():w;return c.reset(),c.snappedToEdge="edge"===M,c.snappedToVertex="vertex"===M,c.worldPos=S,c.worldNormal=x,c.entity=F,c.canvasPos=s,c.snappedCanvasPos=B||s,c}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Se(t,I),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){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.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 in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=t.length;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())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,s)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));t(i)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!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("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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()}}const ze=new e({});class Ke{constructor(e){this.id=ze.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ze.removeItem(this.id)}}class Ye extends N{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Ke({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],s=e[3];this._state.boundary=[0,0,t,s],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 Xe extends N{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),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],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),u.perspectiveMat4(i*(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:2e3;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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class Ze extends N{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),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,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),u.orthoMat4c(n,a,h,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:2e3;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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class qe extends N{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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(){u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Je extends N{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const $e=u.vec3(),et=u.vec3(),tt=u.vec3(),st=u.vec3(),it=u.vec3(),rt=u.vec3(),ot=u.vec4(),nt=u.vec4(),at=u.vec4(),lt=u.mat4(),ht=u.mat4(),ct=u.vec3(),At=u.vec3(),ut=u.vec3(),pt=u.vec3();class dt extends N{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Ke({deviceMatrix:u.mat4(),hasDeviceMatrix:!1,matrix:u.mat4(),normalMatrix:u.mat4(),inverseMatrix:u.mat4()}),this._perspective=new Xe(this),this._ortho=new Ze(this),this._frustum=new qe(this),this._customProjection=new Je(this),this._project=this._perspective,this._eye=u.vec3([0,0,10]),this._look=u.vec3([0,0,0]),this._up=u.vec3([0,1,0]),this._worldUp=u.vec3([0,1,0]),this._worldRight=u.vec3([1,0,0]),this._worldForward=u.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?(u.subVec3(this._eye,this._look,ct),u.normalizeVec3(ct,At),u.mulVec3Scalar(At,1e3,ut),u.addVec3(this._look,ut,pt),t=pt):t=this._eye,e.hasDeviceMatrix?(u.lookAtMat4v(t,this._look,this._up,ht),u.mulMat4(e.deviceMatrix,ht,e.matrix)):u.lookAtMat4v(t,this._look,this._up,e.matrix),u.inverseMat4(this._state.matrix,this._state.inverseMatrix),u.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=u.subVec3(this._eye,this._look,$e);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,lt),t=u.transformPoint3(lt,t,et),this.eye=u.addVec3(this._look,t,tt),this.up=u.transformPoint3(lt,this._up,st)}orbitPitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._eye,this._look,$e);const s=u.cross3Vec3(u.normalizeVec3(t,et),u.normalizeVec3(this._up,tt));u.rotationMat4v(.0174532925*e,s,lt),t=u.transformPoint3(lt,t,st),this.up=u.transformPoint3(lt,this._up,it),this.eye=u.addVec3(t,this._look,rt)}yaw(e){let t=u.subVec3(this._look,this._eye,$e);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,lt),t=u.transformPoint3(lt,t,et),this.look=u.addVec3(t,this._eye,tt),this._gimbalLock&&(this.up=u.transformPoint3(lt,this._up,st))}pitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._look,this._eye,$e);const s=u.cross3Vec3(u.normalizeVec3(t,et),u.normalizeVec3(this._up,tt));u.rotationMat4v(.0174532925*e,s,lt),this.up=u.transformPoint3(lt,this._up,rt),t=u.transformPoint3(lt,t,st),this.look=u.addVec3(t,this._eye,it)}pan(e){const t=u.subVec3(this._eye,this._look,$e),s=[0,0,0];let i;if(0!==e[0]){const r=u.cross3Vec3(u.normalizeVec3(t,[]),u.normalizeVec3(this._up,et));i=u.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=u.mulVec3Scalar(u.normalizeVec3(this._up,tt),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=u.mulVec3Scalar(u.normalizeVec3(t,st),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=u.addVec3(this._eye,s,it),this.look=u.addVec3(this._look,s,rt)}zoom(e){const t=u.subVec3(this._eye,this._look,$e),s=Math.abs(u.lenVec3(t,et)),i=Math.abs(s+e);if(i<.5)return;const r=u.normalizeVec3(t,tt);this.eye=u.addVec3(this._look,u.mulVec3Scalar(r,i),st)}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=u.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 u.lenVec3(u.subVec3(this._look,this._eye,$e))}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}projectWorldPos(e){const t=ot,s=nt,i=at;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,u.mulMat4v4(this.viewMatrix,t,s),u.mulMat4v4(this.projMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class ft extends N{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class mt extends ft{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 s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Ke({type:"dir",dir:u.vec3([1,1,1]),color:u.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=u.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];u.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=u.identityMat4()),u.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new ke(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 yt extends ft{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:u.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 Et extends N{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var gt=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}();const vt=function(){const e=u.mat4(),t=u.mat4();return function(s,i){i=i||u.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return u.identityMat4(e),u.translationMat4v(s,e),u.identityMat4(t),u.scalingMat4v([a/c,l/c,h/c],t),u.mulMat4(e,t,i),i}}();var It=function(){const e=u.mat4(),t=u.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function Rt(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function Pt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const bt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=Tt(e,a,"floor","ceil"),i=Rt(s),o=Pt(e,a,i),o>n&&(r=s,n=o),s=Tt(e,a,"ceil","ceil"),i=Rt(s),o=Pt(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},Dt=p.memory,Nt=u.AABB3();class Ct extends Et{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ke({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 s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=bt.getPositionsBounds(t.positions),i=bt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=bt.getUVBounds(t.uv),i=bt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=bt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.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(),Dt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Dt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new De(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Dt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new De(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),Dt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new De(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Dt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new De(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Dt.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,s=gt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),Dt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=u.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Dt.positions+=this._pickTrianglePositionsBuf.numItems,Dt.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),bt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=bt.getPositionsBounds(e),i=bt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),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),bt.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,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),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),bt.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,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),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,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),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=u.AABB3()),u.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=u.OBB3()),u.positions3ToAABB3(this._state.positions,Nt,this._state.positionsDecodeMatrix),u.AABB3ToOBB3(Nt,this._obb),this._obbDirty=!1),this._obb}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(),Dt.meshes--}}function Ot(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return y.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,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]})}class St extends N{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const xt={opaque:0,mask:1,blend:2},wt=["opaque","mask","blend"];class Mt extends St{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Ke({type:"PhongMaterial",ambient:u.vec3([1,1,1]),diffuse:u.vec3([1,1,1]),specular:u.vec3([1,1,1]),emissive:u.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=xt[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 wt[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()}}const Bt={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 Ft extends St{get type(){return"EmphasisMaterial"}get presets(){return Bt}constructor(e,t={}){super(e,t),this._state=new Ke({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(e=e||"default",this._preset===e)return;const t=Bt[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(Bt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Lt={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 Ut extends St{get type(){return"EdgeMaterial"}get presets(){return Lt}constructor(e,t={}){super(e,t),this._state=new Ke({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=Lt[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(Lt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Ht={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 Gt extends N{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=u.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return Ht}set units(e){e||(e="meters");Ht[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=u.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=u.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 kt extends N{constructor(e,t={}){super(e,t),this._supported=ye.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()}}const Vt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class jt extends St{get type(){return"PointsMaterial"}get presets(){return Vt}constructor(e,t={}){super(e,t),this._state=new Ke({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=Vt[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(Vt).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 Qt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Wt extends St{get type(){return"LinesMaterial"}get presets(){return Qt}constructor(e,t={}){super(e,t),this._state=new Ke({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=Qt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Qt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function zt(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Qe(this,{transparent:i,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 s=[];for(let e=0,i=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=u.vec4([0,0,0,0]),t=u.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,i=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let i;for(let s=0,r=t.length;s0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{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=u.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[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,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],y.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_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)}_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)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_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)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(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}_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}_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 s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}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}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&b.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 s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=zt(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=zt(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}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,s=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=u.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i{r>i&&(i=r,e(...s))}));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.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.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const Yt=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,i=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=s.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.lights.length;e0,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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.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),A=qt(e),u=i.getNumAllocatedSectionPlanes()>0,p=Zt(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&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;"),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(A){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= 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;"),d&&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] = 1.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] = 1.0;"),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(p){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;e0&&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;e0,l=qt(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=Zt(e);t.gammaInput;const d=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;"));p&&(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("}"),d&&(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;m0&&(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 = "+Xt[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("}")),(A||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 = "+Xt[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._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("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._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("}"),s._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;")),s._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;")),s._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;")),s._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;")),s._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 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._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 = "+Xt[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Xt[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Xt[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Xt[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._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)){h&&s._normalMap?(s._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);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._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;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._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);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._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;")),A&&(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||A)&&(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;e0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class ss{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 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] = 1.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] = 1.0;"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.lights.length;e0,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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const is=new e({}),rs=u.vec3(),os=function(e,t){this.id=is.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ss(t),this._allocate(t)},ns={};os.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 s=ns[t];return s||(s=new os(t,e),ns[t]=s,p.memory.programs++),s._useCount++,s},os.prototype.put=function(){0==--this._useCount&&(is.removeItem(this.id),this._program&&this._program.destroy(),delete ns[this._hash],p.memory.programs--)},os.prototype.webglContextRestored=function(){this._program=null},os.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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] = 1.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] = 1.0;"),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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ls=new e({}),hs=u.vec3(),cs=function(e,t){this.id=ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new as(t),this._allocate(t)},As={};cs.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 s=As[t];return s||(s=new cs(t,e),As[t]=s,p.memory.programs++),s._useCount++,s},cs.prototype.put=function(){0==--this._useCount&&(ls.removeItem(this.id),this._program&&this._program.destroy(),delete As[this._hash],p.memory.programs--)},cs.prototype.webglContextRestored=function(){this._program=null},cs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=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=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.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;"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 ps=u.vec3(),ds=function(e,t){this._hash=e,this._shaderSource=new us(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},fs={};ds.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=fs[t];if(!s){if(s=new ds(t,e),s.errors)return console.log(s.errors.join("\n")),null;fs[t]=s,p.memory.programs++}return s._useCount++,s},ds.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete fs[this._hash],p.memory.programs--)},ds.prototype.webglContextRestored=function(){this._program=null},ds.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},ds.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 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 ys=u.vec3(),Es=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ms(t),this._allocate(t)},gs={};Es.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=gs[t];if(!s){if(s=new Es(t,e),s.errors)return console.log(s.errors.join("\n")),null;gs[t]=s,p.memory.programs++}return s._useCount++,s},Es.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete gs[this._hash],p.memory.programs--)},Es.prototype.webglContextRestored=function(){this._program=null},Es.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 Is=u.vec3(),_s=function(e,t){this._hash=e,this._shaderSource=new vs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ts={};_s.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Ts[t];if(!s){if(s=new _s(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ts[t]=s,p.memory.programs++}return s._useCount++,s},_s.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ts[this._hash],p.memory.programs--)},_s.prototype.webglContextRestored=function(){this._program=null},_s.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.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"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Ps=function(e,t){this._hash=e,this._shaderSource=new Rs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},bs={};Ps.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=bs[s];if(!i){if(i=new Ps(s,e),i.errors)return console.log(i.errors.join("\n")),null;bs[s]=i,p.memory.programs++}return i._useCount++,i},Ps.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete bs[this._hash],p.memory.programs--)},Ps.prototype.webglContextRestored=function(){this._program=null},Ps.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Ps.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Hs=function(){const e=u.vec3(),t=u.vec3(),s=u.vec3(),i=u.vec3(),r=u.vec3(),o=u.vec3(),n=u.vec4(),a=u.vec3(),l=u.vec3(),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3(),y=u.vec4(),E=u.vec4(),g=u.vec4(),v=u.vec3(),I=u.vec3(),_=u.vec3(),T=u.vec3(),R=u.vec3(),P=u.vec3(),b=u.vec3(),D=u.vec3(),N=u.vec3(),C=u.vec3(),O=u.vec3();return function(S,x,w,M){var B=M.primIndex;if(null!=B&&B>-1){const G=S.geometry._state,k=S.scene,V=k.camera,j=k.canvas;if("triangles"===G.primitiveName){M.primitive="triangle";const k=B,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var F=Q[k+0],L=Q[k+1],U=Q[k+2];o[0]=F,o[1]=L,o[2]=U,M.indices=o,z=3*F,K=3*L,Y=3*U}else z=3*k,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(bt.decompressPosition(s,e,s),bt.decompressPosition(i,e,i),bt.decompressPosition(r,e,r))}M.canvasPos?u.canvasPosToLocalRay(j.canvas,S.origin?H(x,S.origin):x,w,S.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&u.worldRayToLocalRay(S.worldMatrix,M.origin,M.direction,e,t),u.normalizeVec3(t),u.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,y[0]=n[0],y[1]=n[1],y[2]=n[2],y[3]=1,u.transformVec4(S.worldMatrix,y,E),a[0]=E[0],a[1]=E[1],a[2]=E[2],M.canvasPos&&S.origin&&(a[0]+=S.origin[0],a[1]+=S.origin[1],a[2]+=S.origin[2]),M.worldPos=a,u.transformVec4(V.matrix,E,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,u.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=G.normals;if(X){if(G.compressGeometry){const e=3*F,t=3*L,s=3*U;bt.decompressNormal(X.subarray(e,e+2),c),bt.decompressNormal(X.subarray(t,t+2),A),bt.decompressNormal(X.subarray(s,s+2),p)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],p[0]=X[Y],p[1]=X[Y+1],p[2]=X[Y+2];const e=u.addVec3(u.addVec3(u.mulVec3Scalar(c,h[0],v),u.mulVec3Scalar(A,h[1],I),_),u.mulVec3Scalar(p,h[2],T),R);M.worldNormal=u.normalizeVec3(u.transformVec3(S.worldNormalMatrix,e,P))}const Z=G.uv;if(Z){if(d[0]=Z[2*F],d[1]=Z[2*F+1],f[0]=Z[2*L],f[1]=Z[2*L+1],m[0]=Z[2*U],m[1]=Z[2*U+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(bt.decompressUV(d,e,d),bt.decompressUV(f,e,f),bt.decompressUV(m,e,m))}M.uv=u.addVec3(u.addVec3(u.mulVec2Scalar(d,h[0],b),u.mulVec2Scalar(f,h[1],D),N),u.mulVec2Scalar(m,h[2],C),O)}}}}}();function Gs(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],E=[],g=[],v=[];let I,_,T,R,P,b,D,N,C,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,b=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),E.push(P*T),E.push(x),E.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(b+h),m.push(P*R+c);for(I=0;I0){for(C=m.length/3,E.push(0),E.push(1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(t*T),E.push(1),E.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(C=m.length/3,E.push(0),E.push(-1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(s*T),E.push(-1),E.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=$s(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=$s(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=$s(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,ii(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,ii(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,$s(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,$s(s,this.magFilter)));const a=$s(s,this.format,this.encoding),l=$s(s,this.type),h=si(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class ai extends N{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ke({texture:new ti({gl:this.scene.canvas.gl}),matrix:u.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=u.vec2([0,0]),this._scale=u.vec2([1,1]),this._rotate=u.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),p.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 ti({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,s;0===this._translate[0]&&0===this._translate[1]||(t=u.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=u.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?u.mulMat4(t,s):s),0!==this._rotate&&(s=u.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?u.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=ri(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 s=new Image;s.onload=function(){s=ri(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.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(),p.memory.textures--}}const li=p.memory,hi=u.AABB3();class ci extends Et{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ke({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=u.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=bt.getPositionsBounds(t.positions),o=bt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new De(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),li.positions+=s.positionsBuf.numItems,u.positions3ToAABB3(t.positions,this._aabb),u.positions3ToAABB3(r,hi,s.positionsDecodeMatrix),u.AABB3ToOBB3(hi,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new De(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),li.colors+=s.colorsBuf.numItems}if(t.uv){const e=bt.getUVBounds(t.uv),r=bt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new De(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),li.uvs+=s.uvBuf.numItems}if(t.normals){const e=bt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new De(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),li.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),li.indices+=s.indicesBuf.numItems;const o=gt(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),li.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(),li.meshes--}}var Ai={};function ui(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,E=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,b,D,N=0,C=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],p=[],d=[];let f,m,E,g,v,I,_,T,R,P,b,D;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),E=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(E+a),c.push(g+l),c.push(v+h),p.push(1-_/i),p.push(T/r),I=u.normalizeVec3(u.subVec3([E,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,b=(i+1)*(T-1)+_,D=(i+1)*T+_,d.push(R),d.push(P),d.push(b),d.push(b),d.push(D),d.push(R);return y.apply(e,{positions:c,normals:A,uv:p,indices:d})}Ai.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Ai.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Ai.parse._buffToStr(e));window.location.href=s},Ai.clone=function(e){return JSON.parse(JSON.stringify(e))},Ai.bin={},Ai.bin.f=new Float32Array(1),Ai.bin.fb=new Uint8Array(Ai.bin.f.buffer),Ai.bin.rf=function(e,t){for(var s=Ai.bin.f,i=Ai.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},Ai.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Ai.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Ai.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Ai.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Ai.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Ai.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Ai.parse={},Ai.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class di extends N{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=u.vec3(t.pos||[0,0,0]),this._up=u.vec3(t.up||[0,1,0]),this._normal=u.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=u.vec3(),this._rtcPos=u.vec3(),this._imageSize=u.vec2(),this._texture=new ai(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 Js(this,{matrix:u.inverseMat4(u.lookAtMat4v(this._pos,u.subVec3(this._pos,this._normal,u.mat4()),this._up,u.mat4())),children:[this._bitmapMesh=new Us(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Ct(this,ui({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Mt(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]}}class fi extends N{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=u.vec3(),r=k(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),E=Object.entries(y).map((([e,t])=>({color:e,components:t})));o.components.coloring=E;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),o.components.translucency=this._createBCFComponents(t.xrayedObjectIds),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=_i(e.location,mi),s=_i(e.direction,mi);h&&u.negateVec3(s),u.subVec3(t,l),r.yUp&&(t=Ri(t),s=Ri(s)),new Vs(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),s.push(r++),s.push(r++))})),new fi(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=_i(e.location,yi),n=_i(e.normal,Ei),a=_i(e.up,gi),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=Ri(o),n=Ri(n),a=Ri(a)),new di(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==r.spaces_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const o=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=_i(e.perspective_camera.camera_view_point,mi),h=_i(e.perspective_camera.camera_direction,mi),c=_i(e.perspective_camera.camera_up_vector,mi),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=_i(e.orthogonal_camera.camera_view_point,mi),h=_i(e.orthogonal_camera.camera_direction,mi),c=_i(e.orthogonal_camera.camera_up_vector,mi),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),u.subVec3(a,l),r.yUp&&(a=Ri(a),h=Ri(h),c=Ri(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:u.addVec3(a,h,mi)}else h=u.addVec3(a,h,mi);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=u.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function Ii(e){return{x:e[0],y:e[1],z:e[2]}}function _i(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ti(e){return new Float64Array([e[0],-e[2],e[1]])}function Ri(e){return new Float64Array([e[0],e[2],-e[1]])}const Pi=u.vec3(),bi=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class Di extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._targetMarker=new ie(s,t.target),this._originWorld=u.vec3(),this._targetWorld=u.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new re(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new re(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new re(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new re(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new ne(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new ne(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new ne(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new ne(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(u.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,y=s.unitsInfo[m].abbrev;for(var p=0,d=i.length;p{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=t[0]-5+"px",this._markerDiv.style.marginTop=t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),h=e.entity):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class Oi extends L{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Ci(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.target,i=new Di(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=0)&&(e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),i=!1))}));let o=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{o=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{o=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{o&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class xi{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 s=this._messages[this._locale];if(!s)return null;const i=wi(e,s);return i?t?Mi(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=wi(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=Mi(r,[t]),s&&(r=Mi(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[t];i||(i={},this._eventSubs[t]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function wi(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?Gi._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(u.subVec3(i.eye,i.look,Hi),i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Li),i.look=u.subVec3(Li,Hi,Fi)):this._flyingLook&&(i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Fi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Ui)):this._flyingEyeLookUp&&(i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Li),i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Fi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Ui)),this._projection2){const t="ortho"===this._projection2?Gi._easeOutExpo(e,0,1,1):Gi._easeInCubic(e,0,1,1);i.customProjection.matrix=u.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();b.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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=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 ki extends N{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Gi(this),this._t=0,this.state=ki.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,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case ki.SCRUBBING:return;case ki.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=ki.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case ki.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=ki.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=ki.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=ki.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=ki.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=ki.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=ki.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=ki.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}ki.STOPPED=0,ki.SCRUBBING=1,ki.PLAYING=2,ki.PLAYING_TO=3,u.vec3(),u.vec3(),u.vec3(),u.vec3([0,-1,0]),u.vec4([0,0,0,1]);const Vi=u.vec3();class ji{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,s){this.numObjects=0,this._mask=s?y.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,h=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;$i[0]=s,$i[1]=i,$i[2]=t.blendCutoff,$i[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,$i),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===Zi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Zi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Zi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?Ji:qi)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class rr extends ir{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class or extends rr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class nr extends ir{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class ar extends nr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class lr extends ir{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class hr extends ir{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class cr extends ir{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class Ar extends ir{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class ur extends rr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class pr extends rr{_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,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles 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;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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 = 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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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("outColor = vColor;"),o.push("}"),o}}class fr extends or{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class mr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class yr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = vPickColor; "),i.push("}"),i}}class Er extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class gr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),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(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class vr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),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;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Ir extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class _r extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Tr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),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); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Rr extends rr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&(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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),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(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals 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;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" 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(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class br extends rr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture 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;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),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("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(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("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}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;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e5e6&&(e=5e6),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 Or=u.mat4(),Sr=u.mat4();function xr(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,p=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function Br(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const Fr=u.vec3(),Lr=u.vec3(),Ur=u.vec3(),Hr=u.vec3(),Gr=u.mat4();class kr extends ir{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Fr;let m,y;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=Lr;if(l){const e=Ur;u.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=H(d,t,Gr),y=Hr,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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()}_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,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${u.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Vr=u.vec3(),jr=u.vec3(),Qr=u.vec3(),Wr=u.vec3(),zr=u.mat4();class Kr extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Vr;let m,y;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=jr;if(l){const e=Qr;u.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=H(d,t,zr),y=Wr,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_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 s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Yr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new kr(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new Kr(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new kr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Kr(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Xr={};const Zr=u.mat4(),qr=u.mat4(),Jr=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.OBB3();const $r=u.vec3(),eo=u.vec3(),to=u.vec3(),so=u.vec3(),io=u.vec3(),ro=u.vec3(),oo=u.vec3();class no{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._batchingRenderers=function(e){const t=e.id;let s=Nr[t];return s||(s=new Dr(e),Nr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Nr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=Xr[t];return s||(s=new Yr(e),Xr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Xr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Cr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ke({origin:u.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=u.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=u.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=u.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=u.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=u.collapseAABB3(),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Zr;y?u.inverseMat4(u.transposeMat4(y,qr),e):u.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,p=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=Mr(d,"floor","ceil"),a=Br(n),h=o(d,a),h>c&&(l=n,c=h),n=Mr(d,"ceil","ceil"),a=Br(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,r,r.length,v.normals,v.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):xr(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=u.mat4());if(e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new De(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new De(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=bt.getUVBounds(s.uv),r=bt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=u.mat3(r.decodeMatrix),e.uvBuf=new De(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new De(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,i,s.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,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;eE)&&(E=e,i.set(g),r&&u.triangleNormal(d,f,m,r),y=!0)}}return y&&r&&(u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),y}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 ao extends nr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class lo extends nr{_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,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,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,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// 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 vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class co extends ar{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Ao extends ar{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class uo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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("outColor = vPickColor; "),i.push("}"),i}}class po extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class fo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),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(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class mo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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),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;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class yo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 Eo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),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,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class go extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const vo={3e3:"linearToLinear",3001:"sRGBToLinear"};class Io extends nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&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("}"),i.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 = "+vo[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+vo[i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),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(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" 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(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class To extends nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),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 mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.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 );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(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;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${u.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xo=u.vec3(),wo=u.vec3(),Mo=u.vec3(),Bo=u.vec3(),Fo=u.mat4();class Lo extends ir{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=xo;let m,y;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=wo;if(l){const e=u.transformPoint3(c,l,Mo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=H(d,t,Fo),y=Bo,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(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.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_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,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Uo{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new So(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new Lo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new So(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Lo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Ho={};const Go=new Uint8Array(4),ko=new Float32Array(1),Vo=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]);const jo=new Float32Array(3),Qo=u.vec3(),Wo=u.vec3(),zo=u.vec3(),Ko=u.vec3(),Yo=u.vec3(),Xo=u.vec3(),Zo=u.vec3(),qo=new Float32Array(4);class Jo{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Po[t];return s||(s=new Ro(e),Po[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Po[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=Ho[t];return s||(s=new Uo(e),Ho[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ho[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new Ke({numInstances:0,obb:u.OBB3(),origin:u.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=u.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new De(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new De(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new De(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new De(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=u.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new De(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new De(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new De(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(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,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Go[0]=t[0],Go[1]=t[1],Go[2]=t[2],Go[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Go,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&j),r=!!(t&Y),o=!!(t&X),n=!!(t&Z),a=!!(t&q),l=!!(t&W),h=!!(t&Q);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Zi.NOT_RENDERED:s?Zi.COLOR_TRANSPARENT:Zi.COLOR_OPAQUE,A=!i||h?Zi.NOT_RENDERED:n?Zi.SILHOUETTE_SELECTED:o?Zi.SILHOUETTE_HIGHLIGHTED:r?Zi.SILHOUETTE_XRAYED:Zi.NOT_RENDERED;let u=0;u=!i||h?Zi.NOT_RENDERED:n?Zi.EDGES_SELECTED:o?Zi.EDGES_HIGHLIGHTED:r?Zi.EDGES_XRAYED:a?s?Zi.EDGES_COLOR_TRANSPARENT:Zi.EDGES_COLOR_OPAQUE:Zi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Zi.PICK:Zi.NOT_RENDERED)<<12,p|=(t&z?1:0)<<16,ko[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(ko,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(jo[0]=t[0],jo[1]=t[1],jo[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(jo,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=Vo,p=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&u.triangleNormal(f,m,y,r),E=!0)}}return E&&r&&(u.transformVec3(a.normalMatrix,r,r),u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),E}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 $o extends cr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class en extends cr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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;"),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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class tn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new $o(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new en(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const sn={};class rn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.OBB3();class on{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=sn[t];return s||(s=new tn(e),sn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete sn[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new rn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ke({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=u.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=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=xr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 an extends Ar{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),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 = 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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class ln{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new an(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const hn={};const cn=new Uint8Array(4),An=new Float32Array(1);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]);const un=new Float32Array(3),pn=new Float32Array(4);class dn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=hn[t];return s||(s=new ln(e),hn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete hn[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new Ke({obb:u.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=u.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=u.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(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,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";cn[0]=t[0],cn[1]=t[1],cn[2]=t[2],cn[3]=t[3],this._state.colorsBuf.setData(cn,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&j),r=!!(t&Y),o=!!(t&X),n=!!(t&Z),a=!!(t&q),l=!!(t&W),h=!!(t&Q);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Zi.NOT_RENDERED:s?Zi.COLOR_TRANSPARENT:Zi.COLOR_OPAQUE,A=!i||h?Zi.NOT_RENDERED:n?Zi.SILHOUETTE_SELECTED:o?Zi.SILHOUETTE_HIGHLIGHTED:r?Zi.SILHOUETTE_XRAYED:Zi.NOT_RENDERED;let u=0;u=!i||h?Zi.NOT_RENDERED:n?Zi.EDGES_SELECTED:o?Zi.EDGES_HIGHLIGHTED:r?Zi.EDGES_XRAYED:a?s?Zi.EDGES_COLOR_TRANSPARENT:Zi.EDGES_COLOR_OPAQUE:Zi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Zi.PICK:Zi.NOT_RENDERED)<<12,p|=(t&z?255:0)<<16,An[0]=p,this._state.flagsBuf.setData(An,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(un[0]=t[0],un[1]=t[1],un[2]=t[2],this._state.offsetsBuf.setData(un,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;pn[0]=t[0],pn[1]=t[4],pn[2]=t[8],pn[3]=t[12],this._state.modelMatrixCol0Buf.setData(pn,s),pn[0]=t[1],pn[1]=t[5],pn[2]=t[9],pn[3]=t[13],this._state.modelMatrixCol1Buf.setData(pn,s),pn[0]=t[2],pn[1]=t[6],pn[2]=t[10],pn[3]=t[14],this._state.modelMatrixCol2Buf.setData(pn,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}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 fn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class mn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 yn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class En extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class gn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class vn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new fn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new mn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new yn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new En(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new gn(this._scene)),this._occlusionRenderer}_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()}}const In={};class _n{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}u.vec4(),u.vec4(),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.OBB3();class Tn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=In[t];return s||(s=new vn(e),In[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete In[t],s._destroy()}))),s}(e.model.scene),this._buffer=new _n(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ke({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=u.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=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=xr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Pn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class bn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class Dn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Nn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Cn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 On extends hr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Sn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Rn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Cn(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new bn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Dn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Nn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new On(this._scene)),this._shadowRenderer}_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()}}const xn={};const wn=new Uint8Array(4),Mn=new Float32Array(1);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]);const Bn=new Float32Array(3),Fn=new Float32Array(4);class Ln{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=xn[t];return s||(s=new Sn(e),xn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete xn[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new Ke({obb:u.OBB3(),numInstances:0,origin:e.origin?u.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=u.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let i=!1;s.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new De(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=u.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new De(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new De(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;s.pickColorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(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,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";wn[0]=t[0],wn[1]=t[1],wn[2]=t[2],this._state.colorsBuf.setData(wn,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&j),r=!!(t&Y),o=!!(t&X),n=!!(t&Z),a=!!(t&q),l=!!(t&W),h=!!(t&Q);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Zi.NOT_RENDERED:s?Zi.COLOR_TRANSPARENT:Zi.COLOR_OPAQUE,A=!i||h?Zi.NOT_RENDERED:n?Zi.SILHOUETTE_SELECTED:o?Zi.SILHOUETTE_HIGHLIGHTED:r?Zi.SILHOUETTE_XRAYED:Zi.NOT_RENDERED;let u=0;u=!i||h?Zi.NOT_RENDERED:n?Zi.EDGES_SELECTED:o?Zi.EDGES_HIGHLIGHTED:r?Zi.EDGES_XRAYED:a?s?Zi.EDGES_COLOR_TRANSPARENT:Zi.EDGES_COLOR_OPAQUE:Zi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Zi.PICK:Zi.NOT_RENDERED)<<12,p|=(t&z?255:0)<<16,Mn[0]=p,this._state.flagsBuf.setData(Mn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Bn[0]=t[0],Bn[1]=t[1],Bn[2]=t[2],this._state.offsetsBuf.setData(Bn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;Fn[0]=t[0],Fn[1]=t[4],Fn[2]=t[8],Fn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Fn,s),Fn[0]=t[1],Fn[1]=t[5],Fn[2]=t[9],Fn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Fn,s),Fn[0]=t[2],Fn[1]=t[6],Fn[2]=t[10],Fn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Fn,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.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._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,Zi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,Zi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,Zi.PICK)}drawPickNormals(e,t){}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()}}class Un{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class Hn{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Gn={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={}}};const kn=new class{constructor(e,t,s){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=s}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,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==Vn[e])return void Vn[e].push({onLoad:t,onProgress:s,onError:i});Vn[e]=[],Vn[e].push({onLoad:t,onProgress:s,onError:i});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 s=Vn[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.length;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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Gn.add(e,t);const s=Vn[e];delete Vn[e];for(let e=0,i=s.length;e{const s=Vn[e];if(void 0===s)throw this.manager.itemError(e),t;delete Vn[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Qn{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{const i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Wn=0;class zn{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Qn,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new jn;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new jn;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=zn.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(zn.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(zn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(zn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),Wn>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Wn++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===A?3001:3e3,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Wn--}}zn.BasisFormat={ETC1S:0,UASTC_4x4:1},zn.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},zn.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},zn.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),y=n.getDFDFlags(),{transcoderFormat:E,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const o=this._getNextId(),n=new s(o);for(let s=0,o=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new r(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(i);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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("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;ewindow.innerHeight&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}let n=!0,a=n?Float64Array:Float32Array;const l=new a(3),h=new a(16),c=new a(16),A=new a(4),u={setDoublePrecisionEnabled(e){n=e,a=n?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>n,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new a(e||2),vec3:e=>new a(e||3),vec4:e=>new a(e||4),mat3:e=>new a(e||9),mat3ToMat4:(e,t=new a(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new a(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const i=new a(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new a(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>u.dotVec4(e,e),lenVec4:e=>Math.sqrt(u.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=>u.dotVec3(e,e),sqLenVec2:e=>u.dotVec2(e,e),lenVec3:e=>Math.sqrt(u.sqLenVec3(e)),distVec3:(()=>{const e=new a(3);return(t,s)=>u.lenVec3(u.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(u.sqLenVec2(e)),distVec2:(()=>{const e=new a(2);return(t,s)=>u.lenVec2(u.subVec2(t,s,e))})(),rcpVec3:(e,t)=>u.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/u.lenVec4(e);return u.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/u.lenVec3(e);return u.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/u.lenVec2(e);return u.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=u.dotVec3(e,t)/Math.sqrt(u.sqLenVec3(e)*u.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new a(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=u.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=u.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=u.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||u.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:()=>u.m4s(0),setMat4ToOnes:()=>u.m4s(1),diagonalMat4v:e=>new a([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,i)=>u.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>u.diagonalMat4c(e,e,e,e),identityMat4:(e=new a(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new a(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>u.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],y=e[14],E=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],b=t[7],D=t[8],N=t[9],C=t[10],O=t[11],S=t[12],x=t[13],w=t[14],M=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*y,s[3]=g*n+v*c+I*d+_*E,s[4]=T*i+R*a+P*A+b*f,s[5]=T*r+R*l+P*u+b*m,s[6]=T*o+R*h+P*p+b*y,s[7]=T*n+R*c+P*d+b*E,s[8]=D*i+N*a+C*A+O*f,s[9]=D*r+N*l+C*u+O*m,s[10]=D*o+N*h+C*p+O*y,s[11]=D*n+N*c+C*d+O*E,s[12]=S*i+x*a+w*A+M*f,s[13]=S*r+x*l+w*u+M*m,s[14]=S*o+x*h+w*p+M*y,s[15]=S*n+x*c+w*d+M*E,s},mulMat3(e,t,s){s||(s=new a(9));const i=e[0],r=e[3],o=e[6],n=e[1],l=e[4],h=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],y=t[4],E=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*y+o*v,s[6]=i*f+r*E+o*I,s[1]=n*p+l*m+h*g,s[4]=n*d+l*y+h*v,s[7]=n*f+l*E+h*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*y+u*v,s[8]=c*f+A*E+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=u.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],y=e[15],E=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,b=c*y-p*d,D=A*m-u*f,N=A*y-p*f,C=u*y-p*m,O=1/(E*C-g*N+v*D+I*b-_*P+T*R);return t[0]=(a*C-l*N+h*D)*O,t[1]=(-i*C+r*N-o*D)*O,t[2]=(f*T-m*_+y*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*C+l*b-h*P)*O,t[5]=(s*C-r*b+o*P)*O,t[6]=(-d*T+m*v-y*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*N-a*b+h*R)*O,t[9]=(-s*N+i*b-o*R)*O,t[10]=(d*_-f*v+y*E)*O,t[11]=(-c*_+A*v-p*E)*O,t[12]=(-n*D+a*P-l*R)*O,t[13]=(s*D-i*P+r*R)*O,t[14]=(-d*I+f*g-m*E)*O,t[15]=(c*I-A*g+u*E)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||u.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||u.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new a(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.translationMat4v(e,r))})(),translationMat4s:(e,t)=>u.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>u.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=u.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,p,d,f,m;return c=a*l,A=l*h,p=h*a,d=a*r,f=l*r,m=h*r,(s=s||u.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*p-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*p+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>u.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=u.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=u.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new a(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>u.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=u.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,p=i*h,d=r*l,f=r*h,m=o*h,y=n*a,E=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=p-E,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+y,s[7]=0,s[8]=p+E,s[9]=f-y,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=u.vec4()){const i=u.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],p=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,p),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,p),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,p),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,p),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,p))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,p),s[1]=0)),s},composeMat4:(e,t,s,i=u.mat4())=>(u.quaternionToRotationMat4(t,i),u.scaleMat4v(s,i),u.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new a(3),t=new a(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=u.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=u.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=u.lenVec3(e);u.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,u.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=u.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],p=t[2];if(r===c&&o===A&&n===p)return u.identityMat4();let d,f,m,y,E,g,v,I,_,T;return d=r-c,f=o-A,m=n-p,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,y=l*m-h*f,E=h*d-a*m,g=a*f-l*d,T=Math.sqrt(y*y+E*E+g*g),T?(T=1/T,y*=T,E*=T,g*=T):(y=0,E=0,g=0),v=f*g-m*E,I=m*y-d*g,_=d*E-f*y,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=y,i[1]=v,i[2]=d,i[3]=0,i[4]=E,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(y*r+E*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>u.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=u.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];u.addVec4(r,i,h),u.subVec4(r,i,c);const o=2*i[2],n=c[0],a=c[1],l=c[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=h[0]/n,s[9]=h[1]/a,s[10]=-h[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],u.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,s=u.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=u.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],y=e[8],E=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new a(16),t=new a(16),s=new a(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||u.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||u.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=u.vec4()){const i=e[0]*u.DEGTORAD/2,r=e[1]*u.DEGTORAD/2,o=e[2]*u.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=u.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const p=s+n+c;return p>0?(A=.5/Math.sqrt(p+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=u.vec4()){const i=Math.sqrt(u.dotVec3(e,e)*u.dotVec3(t,t));let r=i+u.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):u.cross3Vec3(e,t,s),s[3]=r,u.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=u.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new a(16);return(t,s,i)=>(i=i||u.vec3(),u.quaternionToRotationMat4(t,e),u.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=u.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=u.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,p=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-p*-a,s[1]=A*h+d*-a+p*-n-c*-l,s[2]=p*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=u.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,p=n*s,d=a*s,f=l*s,m=a*i,y=l*i,E=l*r;return t[0]=1-(m+E),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(p+E),t[6]=y+h,t[8]=f+c,t[9]=y-h,t[10]=1-(p+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,y=o*l;return t[0]=1-(u+d),t[4]=c-y,t[8]=A+m,t[1]=c+y,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+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 s=u.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,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)=>u.normalizeQuaternion(u.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=u.vec4()){const s=(e=u.normalizeQuaternion(e,A))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,t},AABB3:e=>new a(e||6),AABB2:e=>new a(e||4),OBB3:e=>new a(e||32),OBB2:e=>new a(e||16),Sphere3:(e,t,s,i)=>new a([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],y=e[9],E=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new a(3),t=new a(3),s=new a(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],u.subVec3(t,e,s),Math.abs(u.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new a(3),t=new a(3),s=new a(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=u.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(u.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||u.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||u.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=u.AABB3())=>(e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MAX_DOUBLE,e[3]=u.MIN_DOUBLE,e[4]=u.MIN_DOUBLE,e[5]=u.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=u.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new a(3);return(t,s,i)=>{s=s||u.AABB3();let r,o,n,a=u.MAX_DOUBLE,l=u.MAX_DOUBLE,h=u.MAX_DOUBLE,c=u.MIN_DOUBLE,A=u.MIN_DOUBLE,p=u.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>p&&(p=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=p,s}})(),OBB3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new a(3);return(t,s)=>{s=s||u.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=u.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=u.vec3()){let s=0,i=0,r=0;for(var o=0,n=e.length;o(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](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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MIN_DOUBLE,e[3]=u.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=u.AABB2()){let s,i,r,o,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=u.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,p=r*l-o*a,d=Math.sqrt(c*c+A*A+p*p);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=p/d),i},rayTriangleIntersect:(()=>{const e=new a(3),t=new a(3),s=new a(3),i=new a(3),r=new a(3);return(o,n,a,l,h,c)=>{c=c||u.vec3();const A=u.subVec3(l,a,e),p=u.subVec3(h,a,t),d=u.cross3Vec3(n,p,s),f=u.dotVec3(A,d);if(f<1e-6)return null;const m=u.subVec3(o,a,i),y=u.dotVec3(m,d);if(y<0||y>f)return null;const E=u.cross3Vec3(m,A,r),g=u.dotVec3(n,E);if(g<0||y+g>f)return null;const v=u.dotVec3(p,E)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new a(3),t=new a(3),s=new a(3),i=new a(3);return(r,o,n,a,l,h)=>{h=h||u.vec3(),o=u.normalizeVec3(o,e);const c=u.subVec3(a,n,t),A=u.subVec3(l,n,s),p=u.cross3Vec3(c,A,i);u.normalizeVec3(p,p);const d=-u.dotVec3(n,p),f=-(u.dotVec3(r,p)+d)/u.dotVec3(o,p);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new a(3),t=new a(3),s=new a(3);return(i,r,o,n,a)=>{const l=u.subVec3(n,r,e),h=u.subVec3(o,r,t),c=u.subVec3(i,r,s),A=u.dotVec3(l,l),p=u.dotVec3(l,h),d=u.dotVec3(l,c),f=u.dotVec3(h,h),m=u.dotVec3(h,c),y=A*f-p*p;if(0===y)return null;const E=1/y,g=(f*d-p*m)*E,v=(A*m-p*d)*E;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=u.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,y=0;for(f=0,m=e.length;f{const e=new a(3),t=new a(3),s=new a(3),i=new a(3),r=new a(3),o=new a(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let p,d,f,m,y,E,g;for(h=0,c=a.length;h{const e=new a(3),t=new a(3),s=new a(3),i=new a(3),r=new a(3),o=new a(3),n=new a(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const p=1e4;let d,f,m,y,E,g;for(f=0,y=e.length;f{const e=new a(4),t=new a(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,u.transformVec4(s,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],u.transformVec3(s,e,t),u.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new a(16),t=new a(16),s=new a(4),i=new a(4),r=new a(4),o=new a(4);return(n,a,l,h,c,A)=>{const p=u.mulMat4(l,a,e),d=u.inverseMat4(p,t),f=n.width,m=n.height,y=(h[0]-f/2)/(f/2),E=-(h[1]-m/2)/(m/2);s[0]=y,s[1]=E,s[2]=-1,s[3]=1,u.transformVec4(d,s,i),u.mulVec4Scalar(i,1/i[3]),r[0]=y,r[1]=E,r[2]=1,r[3]=1,u.transformVec4(d,r,o),u.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],u.subVec3(o,i,A),u.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new a(3),t=new a(3);return(s,i,r,o,n,a,l)=>{u.canvasPosToWorldRay(s,i,r,n,e,t),u.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new a(16),t=new a(4),s=new a(4);return(i,r,o,n,a)=>{const l=u.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],u.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new a(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let h,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,h=0,c=s.length;hn[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(s.length<20||o>10)return l.triangles=s,l.leaf=!0,l;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),l.splitDim=u;const p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let y=0;for(h=0,c=s.length;h{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};u.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}(),u.planeClipsPositions3=function(e,t,s,i=3){for(let r=0,o=s.length;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;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),s=new Uint8Array(e);for(var n=0;n=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}},I={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},_=[];let T,R=0,P=0;const b=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(b.scenes[e.id])return void console.error(`[ERROR] Scene ${y.inQuotes(e.id)} already exists`)}else e.id=g.addItem({});b.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;E[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},p.components.scenes++,e.once("destroyed",(()=>{g.removeItem(e.id),delete b.scenes[e.id],delete E[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in b.scenes)b.scenes.hasOwnProperty(t)&&(e=b.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete b.scenes[e.id]))},this.scheduleTask=function(e,t){v.push(e),v.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;v.length>0&&(e<0||i0&&T>0){var t=1e3/T;P+=t,_.push(t),_.length>=30&&(P-=_.shift()),p.frame.fps=Math.round(P/_.length)}!function(e){const t=b.runTasks(e+10),s=b.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=s,p.frame.tasksBudget=10}(e),function(e){for(var t in I.time=e,b.scenes)if(b.scenes.hasOwnProperty(t)){var s=b.scenes[t];I.sceneId=t,I.startTime=s.startTime,I.deltaTime=null!=I.prevTime?I.time-I.prevTime:0,s.fire("tick",I,!0)}I.prevTime=e}(e),function(){const e=b.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=E[n],i||(i=E[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),R=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(D)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(D);class N{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 N))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,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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 s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(y.isNumeric(s)||y.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+y.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+y.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+y.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():b.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_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,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class w{constructor(){this.planes=[new x,new x,new x,new x,new x,new x]}}function M(e,t,s){const i=u.mulMat4(s,t,S),r=i[0],o=i[1],n=i[2],a=i[3],l=i[4],h=i[5],c=i[6],A=i[7],p=i[8],d=i[9],f=i[10],m=i[11],y=i[12],E=i[13],g=i[14],v=i[15];e.planes[0].set(a-r,A-l,m-p,v-y),e.planes[1].set(a+r,A+l,m+p,v+y),e.planes[2].set(a-o,A-h,m-d,v-E),e.planes[3].set(a+o,A+h,m+d,v+E),e.planes[4].set(a-n,A-c,m-f,v-g),e.planes[5].set(a+n,A+c,m+f,v+g)}function B(e,t){let s=w.INSIDE;const i=C,r=O;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return w.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=w.INTERSECT)}return s}w.INSIDE=0,w.INTERSECT=1,w.OUTSIDE=2;class F extends N{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=u.vec2(),this._canvasMarqueeCorner2=u.vec2(),this._canvasMarquee=u.AABB2(),this._marqueeFrustum=new w,this._marqueeFrustumProjMat=u.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!==F.PICK_MODE_INSIDE&&e!==F.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===F.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=(s,i=w.INTERSECT)=>{if(i===w.INTERSECT&&(i=B(this._marqueeFrustum,s.aabb)),i!==w.OUTSIDE){if(s.entities){const t=s.entities;for(let s=0,i=t.length;s3||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,s=e.clientHeight,i=e.clientLeft,r=e.clientTop,o=2/t,n=2/s,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-i)*o-1,h=(this._canvasMarquee[2]-i)*o-1,c=-(this._canvasMarquee[3]-r)*n+1,A=-(this._canvasMarquee[1]-r)*n+1,p=this.viewer.scene.camera.frustum.near*(17*a);u.frustumMat4(l,h,c*a,A*a,p,1e4,this._marqueeFrustumProjMat),M(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)}}F.PICK_MODE_INTERSECTS=0,F.PICK_MODE_INSIDE=1;class L{constructor(e,t,s){this.id=s&&s.id?s.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)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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)}}const U=u.vec3(),H=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(i,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(i,t,s),u.setMat4Translation(i,s,o),o.slice()}}();function G(e,t,s){const i=Float32Array.from([e[0]])[0],r=e[0]-i,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=i,t[1]=o,t[2]=a,s[0]=r,s[1]=n,s[2]=l}function k(e,t,s,i=1e3){const r=u.getPositionsCenter(e,U),o=Math.round(r[0]/i)*i,n=Math.round(r[1]/i)*i,a=Math.round(r[2]/i)*i;s[0]=o,s[1]=n,s[2]=a;const l=0!==s[0]||0!==s[1]||0!==s[2];if(l)for(let s=0,i=e.length;s0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(u.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){te.set(this._viewPos),te[3]=1,u.transformPoint4(this.scene.camera.projMatrix,te,se);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+se[0]/se[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-se[1]/se[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){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof ee?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)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),G(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._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class re{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class oe{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!0,this._culled=!1;var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ne{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var ae=u.vec3(),le=u.vec3();class he extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._cornerMarker=new ie(s,t.corner),this._targetMarker=new ie(s,t.target),this._originWorld=u.vec3(),this._cornerWorld=u.vec3(),this._targetWorld=u.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new re(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new re(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new ne(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(u.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const p=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>p||f>p||m>p)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const y=this._container.getBoundingClientRect();for(var r=i.top-y.top,o=i.left-y.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const s=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),h.set(s),this._mouseState){case 0:this.markerDiv.style.marginLeft=s[0]-5+"px",this.markerDiv.style.marginTop=s[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,i&&(i.visible=!0,i.pointerPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class ue extends L{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new Ae(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.corner,i=e.target,r=new he(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t
',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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.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 s=this._element;s&&(s.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 de=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class fe extends N{constructor(e,t={}){super(e,t),this._backgroundColor=u.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 s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new pe(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-"+u.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?ye.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?ye.FS_MAX_FLOAT_PRECISION="mediump":ye.FS_MAX_FLOAT_PRECISION="lowp":ye.FS_MAX_FLOAT_PRECISION="mediump",ye.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),ye.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),ye.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),ye.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),ye.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ye.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),ye.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),ye.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),ye.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),ye.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){ye.SUPPORTED_EXTENSIONS[e]=!0})))}class ge{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}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}}class ve{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function Pe(e){console.error(e.join("\n"))}class be{constructor(e,t){this.id=Te.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 ve(e,e.VERTEX_SHADER,Re(this.source.vertex)),this._fragmentShader=new ve(e,e.FRAGMENT_SHADER,Re(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Pe(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Pe(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Pe(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Pe(this.errors);let t,s,i,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 Pe(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ne{constructor(e,t){this.scene=e,this.aabb=u.AABB3(),this.origin=u.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-t){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{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 s=this._occlusionLayers[t];s||(s=new Ne(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ne(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.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;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new be(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),p=Math.random(),d="perspective"===i.camera.projection;xe[0]=o,xe[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,xe),t.uniform1f(this._uRandomSeed,p);const f=e.getDepthTexture();s.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)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new be(s,{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 i=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 De(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new De(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new De(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.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 Me=new Float32Array(Ge(17,[0,1])),Be=new Float32Array(Ge(17,[1,0])),Fe=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(He(i,t));return s}(17,4)),Le=new Float32Array(2);class Ue{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 be(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]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new De(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new De(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new De(e,e.ELEMENT_ARRAY_BUFFER,i,i.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,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Le[0]=n,Le[1]=a,i.uniform2fv(this._uViewport,Le),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Be):i.uniform2fv(this._uSampleOffsets,Me),i.uniform1fv(this._uSampleWeights,Fe);const A=e.getDepthTexture(),p=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,p,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function He(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Ge(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class ke{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.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,s=null){const i=this.gl,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),s?i.texStorage2D(i.TEXTURE_2D,1,s,e,t):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),r}_touch(...e){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;this.buffer.textures.forEach((e=>i.deleteTexture(e))),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,s,e)))):r.push(this.createTexture(t,s)),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();i.bindFramebuffer(i.FRAMEBUFFER,a);for(let e=0;e0&&i.drawBuffers(r.map(((e,t)=>i.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.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:s},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,s=null,i=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,h=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,s||c.RGBA,i||c.UNSIGNED_BYTE,h,0),h}readArray(e=null,t=null,s=Uint8Array,i=4,r=0){const o=new s(this.buffer.width*this.buffer.height*i),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(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;ee.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 Ve{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let i=s[e];return i||(i=new ke(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=i),i}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function je(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=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":s=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":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}const Qe=function(t,s){s=s||{};const i=new me(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!s.transparent,a=s.alphaDepthMask,l=new e({});let h={},c={},A=!0,d=!0,f=!0,m=!0,y=!0,E=!0,g=!0,v=!0;const I=new Ve(t);let _=!1;const T=new we(t),R=new Ue(t);function P(){A&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableMap,i=t.drawableListPreCull;let r=0;for(let e in s)s.hasOwnProperty(e)&&(i[r++]=s[e]);i.length=r}}(),A=!1,d=!0),d&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),d=!1,f=!0),f&&function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableListPreCull,i=t.drawableList;let r=0;for(let e=0,t=s.length;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=p.size[0],i=t%s-Math.floor(s/2),r=Math.floor(t/s)-Math.floor(s/2),o=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));D.push({x:i,y:r,dist:o,isVertex:n&&a?E[e+3]>y.length/2:n,result:[E[e+0],E[e+1],E[e+2],E[e+3]],normal:[g[e+0],g[e+1],g[e+2],g[e+3]],id:[v[e+0],v[e+1],v[e+2],v[e+3]]})}let S=null,x=null,w=null,M=null;if(D.length>0){D.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),M=D[0].isVertex?"vertex":"edge";const e=D[0].result,t=D[0].normal,s=D[0].id,i=y[e[3]],r=i.origin,o=i.coordinateScale;x=u.normalizeVec3([t[0]/u.MAX_INT,t[1]/u.MAX_INT,t[2]/u.MAX_INT]),S=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],w=l.items[s[0]+(s[1]<<8)+(s[2]<<16)+(s[3]<<24)]}if(null===_&&null==S)return null;let B=null;null!==S&&(B=t.camera.projectWorldPos(S));const F=w&&w.delegatePickedEntity?w.delegatePickedEntity():w;return c.reset(),c.snappedToEdge="edge"===M,c.snappedToVertex="vertex"===M,c.worldPos=S,c.worldNormal=x,c.entity=F,c.canvasPos=s,c.snappedCanvasPos=B||s,c}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Se(t,I),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){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.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 in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=t.length;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())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,s)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));t(i)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!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("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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()}}const ze=new e({});class Ke{constructor(e){this.id=ze.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ze.removeItem(this.id)}}class Ye extends N{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Ke({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],s=e[3];this._state.boundary=[0,0,t,s],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 Xe extends N{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),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],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),u.perspectiveMat4(i*(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:2e3;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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class Ze extends N{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),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,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),u.orthoMat4c(n,a,h,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:2e3;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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class qe extends N{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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(){u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Je extends N{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ke({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const $e=u.vec3(),et=u.vec3(),tt=u.vec3(),st=u.vec3(),it=u.vec3(),rt=u.vec3(),ot=u.vec4(),nt=u.vec4(),at=u.vec4(),lt=u.mat4(),ht=u.mat4(),ct=u.vec3(),At=u.vec3(),ut=u.vec3(),pt=u.vec3();class dt extends N{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Ke({deviceMatrix:u.mat4(),hasDeviceMatrix:!1,matrix:u.mat4(),normalMatrix:u.mat4(),inverseMatrix:u.mat4()}),this._perspective=new Xe(this),this._ortho=new Ze(this),this._frustum=new qe(this),this._customProjection=new Je(this),this._project=this._perspective,this._eye=u.vec3([0,0,10]),this._look=u.vec3([0,0,0]),this._up=u.vec3([0,1,0]),this._worldUp=u.vec3([0,1,0]),this._worldRight=u.vec3([1,0,0]),this._worldForward=u.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?(u.subVec3(this._eye,this._look,ct),u.normalizeVec3(ct,At),u.mulVec3Scalar(At,1e3,ut),u.addVec3(this._look,ut,pt),t=pt):t=this._eye,e.hasDeviceMatrix?(u.lookAtMat4v(t,this._look,this._up,ht),u.mulMat4(e.deviceMatrix,ht,e.matrix)):u.lookAtMat4v(t,this._look,this._up,e.matrix),u.inverseMat4(this._state.matrix,this._state.inverseMatrix),u.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=u.subVec3(this._eye,this._look,$e);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,lt),t=u.transformPoint3(lt,t,et),this.eye=u.addVec3(this._look,t,tt),this.up=u.transformPoint3(lt,this._up,st)}orbitPitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._eye,this._look,$e);const s=u.cross3Vec3(u.normalizeVec3(t,et),u.normalizeVec3(this._up,tt));u.rotationMat4v(.0174532925*e,s,lt),t=u.transformPoint3(lt,t,st),this.up=u.transformPoint3(lt,this._up,it),this.eye=u.addVec3(t,this._look,rt)}yaw(e){let t=u.subVec3(this._look,this._eye,$e);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,lt),t=u.transformPoint3(lt,t,et),this.look=u.addVec3(t,this._eye,tt),this._gimbalLock&&(this.up=u.transformPoint3(lt,this._up,st))}pitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._look,this._eye,$e);const s=u.cross3Vec3(u.normalizeVec3(t,et),u.normalizeVec3(this._up,tt));u.rotationMat4v(.0174532925*e,s,lt),this.up=u.transformPoint3(lt,this._up,rt),t=u.transformPoint3(lt,t,st),this.look=u.addVec3(t,this._eye,it)}pan(e){const t=u.subVec3(this._eye,this._look,$e),s=[0,0,0];let i;if(0!==e[0]){const r=u.cross3Vec3(u.normalizeVec3(t,[]),u.normalizeVec3(this._up,et));i=u.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=u.mulVec3Scalar(u.normalizeVec3(this._up,tt),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=u.mulVec3Scalar(u.normalizeVec3(t,st),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=u.addVec3(this._eye,s,it),this.look=u.addVec3(this._look,s,rt)}zoom(e){const t=u.subVec3(this._eye,this._look,$e),s=Math.abs(u.lenVec3(t,et)),i=Math.abs(s+e);if(i<.5)return;const r=u.normalizeVec3(t,tt);this.eye=u.addVec3(this._look,u.mulVec3Scalar(r,i),st)}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=u.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 u.lenVec3(u.subVec3(this._look,this._eye,$e))}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}projectWorldPos(e){const t=ot,s=nt,i=at;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,u.mulMat4v4(this.viewMatrix,t,s),u.mulMat4v4(this.projMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class ft extends N{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class mt extends ft{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 s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Ke({type:"dir",dir:u.vec3([1,1,1]),color:u.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=u.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];u.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=u.identityMat4()),u.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new ke(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 yt extends ft{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:u.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 Et extends N{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var gt=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}();const vt=function(){const e=u.mat4(),t=u.mat4();return function(s,i){i=i||u.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return u.identityMat4(e),u.translationMat4v(s,e),u.identityMat4(t),u.scalingMat4v([a/c,l/c,h/c],t),u.mulMat4(e,t,i),i}}();var It=function(){const e=u.mat4(),t=u.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function Rt(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function Pt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const bt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=Tt(e,a,"floor","ceil"),i=Rt(s),o=Pt(e,a,i),o>n&&(r=s,n=o),s=Tt(e,a,"ceil","ceil"),i=Rt(s),o=Pt(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},Dt=p.memory,Nt=u.AABB3();class Ct extends Et{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ke({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 s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=bt.getPositionsBounds(t.positions),i=bt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=bt.getUVBounds(t.uv),i=bt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=bt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.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(),Dt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Dt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new De(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Dt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new De(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),Dt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new De(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Dt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new De(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Dt.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,s=gt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),Dt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=u.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Dt.positions+=this._pickTrianglePositionsBuf.numItems,Dt.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),bt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=bt.getPositionsBounds(e),i=bt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),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),bt.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,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),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),bt.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,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),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,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),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=u.AABB3()),u.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=u.OBB3()),u.positions3ToAABB3(this._state.positions,Nt,this._state.positionsDecodeMatrix),u.AABB3ToOBB3(Nt,this._obb),this._obbDirty=!1),this._obb}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(),Dt.meshes--}}function Ot(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return y.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,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]})}class St extends N{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const xt={opaque:0,mask:1,blend:2},wt=["opaque","mask","blend"];class Mt extends St{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Ke({type:"PhongMaterial",ambient:u.vec3([1,1,1]),diffuse:u.vec3([1,1,1]),specular:u.vec3([1,1,1]),emissive:u.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=xt[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 wt[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()}}const Bt={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 Ft extends St{get type(){return"EmphasisMaterial"}get presets(){return Bt}constructor(e,t={}){super(e,t),this._state=new Ke({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(e=e||"default",this._preset===e)return;const t=Bt[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(Bt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Lt={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 Ut extends St{get type(){return"EdgeMaterial"}get presets(){return Lt}constructor(e,t={}){super(e,t),this._state=new Ke({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=Lt[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(Lt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Ht={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 Gt extends N{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=u.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return Ht}set units(e){e||(e="meters");Ht[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=u.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=u.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 kt extends N{constructor(e,t={}){super(e,t),this._supported=ye.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()}}const Vt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class jt extends St{get type(){return"PointsMaterial"}get presets(){return Vt}constructor(e,t={}){super(e,t),this._state=new Ke({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=Vt[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(Vt).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 Qt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Wt extends St{get type(){return"LinesMaterial"}get presets(){return Qt}constructor(e,t={}){super(e,t),this._state=new Ke({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=Qt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Qt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function zt(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Qe(this,{transparent:i,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 s=[];for(let e=0,i=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=u.vec4([0,0,0,0]),t=u.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,i=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let i;for(let s=0,r=t.length;s0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{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=u.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[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,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],y.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_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)}_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)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_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)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(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}_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}_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 s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}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}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&b.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 s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=zt(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=zt(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}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,s=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=u.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i{r>i&&(i=r,e(...s))}));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.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.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const Yt=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,i=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=s.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.lights.length;e0,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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.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),A=qt(e),u=i.getNumAllocatedSectionPlanes()>0,p=Zt(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&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;"),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(A){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= 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;"),d&&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] = 1.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] = 1.0;"),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(p){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;e0&&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;e0,l=qt(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=Zt(e);t.gammaInput;const d=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;"));p&&(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("}"),d&&(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;m0&&(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 = "+Xt[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("}")),(A||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 = "+Xt[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._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("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._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("}"),s._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;")),s._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;")),s._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;")),s._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;")),s._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 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._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 = "+Xt[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Xt[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Xt[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Xt[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._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)){h&&s._normalMap?(s._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);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._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;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._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);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._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;")),A&&(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||A)&&(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;e0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class ss{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 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] = 1.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] = 1.0;"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.lights.length;e0,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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const is=new e({}),rs=u.vec3(),os=function(e,t){this.id=is.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ss(t),this._allocate(t)},ns={};os.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 s=ns[t];return s||(s=new os(t,e),ns[t]=s,p.memory.programs++),s._useCount++,s},os.prototype.put=function(){0==--this._useCount&&(is.removeItem(this.id),this._program&&this._program.destroy(),delete ns[this._hash],p.memory.programs--)},os.prototype.webglContextRestored=function(){this._program=null},os.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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] = 1.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] = 1.0;"),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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ls=new e({}),hs=u.vec3(),cs=function(e,t){this.id=ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new as(t),this._allocate(t)},As={};cs.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 s=As[t];return s||(s=new cs(t,e),As[t]=s,p.memory.programs++),s._useCount++,s},cs.prototype.put=function(){0==--this._useCount&&(ls.removeItem(this.id),this._program&&this._program.destroy(),delete As[this._hash],p.memory.programs--)},cs.prototype.webglContextRestored=function(){this._program=null},cs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=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=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.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;"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 ps=u.vec3(),ds=function(e,t){this._hash=e,this._shaderSource=new us(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},fs={};ds.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=fs[t];if(!s){if(s=new ds(t,e),s.errors)return console.log(s.errors.join("\n")),null;fs[t]=s,p.memory.programs++}return s._useCount++,s},ds.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete fs[this._hash],p.memory.programs--)},ds.prototype.webglContextRestored=function(){this._program=null},ds.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},ds.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 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 ys=u.vec3(),Es=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ms(t),this._allocate(t)},gs={};Es.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=gs[t];if(!s){if(s=new Es(t,e),s.errors)return console.log(s.errors.join("\n")),null;gs[t]=s,p.memory.programs++}return s._useCount++,s},Es.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete gs[this._hash],p.memory.programs--)},Es.prototype.webglContextRestored=function(){this._program=null},Es.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 Is=u.vec3(),_s=function(e,t){this._hash=e,this._shaderSource=new vs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ts={};_s.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Ts[t];if(!s){if(s=new _s(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ts[t]=s,p.memory.programs++}return s._useCount++,s},_s.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ts[this._hash],p.memory.programs--)},_s.prototype.webglContextRestored=function(){this._program=null},_s.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.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"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Ps=function(e,t){this._hash=e,this._shaderSource=new Rs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},bs={};Ps.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=bs[s];if(!i){if(i=new Ps(s,e),i.errors)return console.log(i.errors.join("\n")),null;bs[s]=i,p.memory.programs++}return i._useCount++,i},Ps.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete bs[this._hash],p.memory.programs--)},Ps.prototype.webglContextRestored=function(){this._program=null},Ps.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Ps.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Hs=function(){const e=u.vec3(),t=u.vec3(),s=u.vec3(),i=u.vec3(),r=u.vec3(),o=u.vec3(),n=u.vec4(),a=u.vec3(),l=u.vec3(),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3(),y=u.vec4(),E=u.vec4(),g=u.vec4(),v=u.vec3(),I=u.vec3(),_=u.vec3(),T=u.vec3(),R=u.vec3(),P=u.vec3(),b=u.vec3(),D=u.vec3(),N=u.vec3(),C=u.vec3(),O=u.vec3();return function(S,x,w,M){var B=M.primIndex;if(null!=B&&B>-1){const G=S.geometry._state,k=S.scene,V=k.camera,j=k.canvas;if("triangles"===G.primitiveName){M.primitive="triangle";const k=B,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var F=Q[k+0],L=Q[k+1],U=Q[k+2];o[0]=F,o[1]=L,o[2]=U,M.indices=o,z=3*F,K=3*L,Y=3*U}else z=3*k,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(bt.decompressPosition(s,e,s),bt.decompressPosition(i,e,i),bt.decompressPosition(r,e,r))}M.canvasPos?u.canvasPosToLocalRay(j.canvas,S.origin?H(x,S.origin):x,w,S.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&u.worldRayToLocalRay(S.worldMatrix,M.origin,M.direction,e,t),u.normalizeVec3(t),u.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,y[0]=n[0],y[1]=n[1],y[2]=n[2],y[3]=1,u.transformVec4(S.worldMatrix,y,E),a[0]=E[0],a[1]=E[1],a[2]=E[2],M.canvasPos&&S.origin&&(a[0]+=S.origin[0],a[1]+=S.origin[1],a[2]+=S.origin[2]),M.worldPos=a,u.transformVec4(V.matrix,E,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,u.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=G.normals;if(X){if(G.compressGeometry){const e=3*F,t=3*L,s=3*U;bt.decompressNormal(X.subarray(e,e+2),c),bt.decompressNormal(X.subarray(t,t+2),A),bt.decompressNormal(X.subarray(s,s+2),p)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],p[0]=X[Y],p[1]=X[Y+1],p[2]=X[Y+2];const e=u.addVec3(u.addVec3(u.mulVec3Scalar(c,h[0],v),u.mulVec3Scalar(A,h[1],I),_),u.mulVec3Scalar(p,h[2],T),R);M.worldNormal=u.normalizeVec3(u.transformVec3(S.worldNormalMatrix,e,P))}const Z=G.uv;if(Z){if(d[0]=Z[2*F],d[1]=Z[2*F+1],f[0]=Z[2*L],f[1]=Z[2*L+1],m[0]=Z[2*U],m[1]=Z[2*U+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(bt.decompressUV(d,e,d),bt.decompressUV(f,e,f),bt.decompressUV(m,e,m))}M.uv=u.addVec3(u.addVec3(u.mulVec2Scalar(d,h[0],b),u.mulVec2Scalar(f,h[1],D),N),u.mulVec2Scalar(m,h[2],C),O)}}}}}();function Gs(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],E=[],g=[],v=[];let I,_,T,R,P,b,D,N,C,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,b=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),E.push(P*T),E.push(x),E.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(b+h),m.push(P*R+c);for(I=0;I0){for(C=m.length/3,E.push(0),E.push(1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(t*T),E.push(1),E.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(C=m.length/3,E.push(0),E.push(-1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(s*T),E.push(-1),E.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=$s(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=$s(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=$s(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,ii(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,ii(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,$s(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,$s(s,this.magFilter)));const a=$s(s,this.format,this.encoding),l=$s(s,this.type),h=si(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class ai extends N{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ke({texture:new ti({gl:this.scene.canvas.gl}),matrix:u.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=u.vec2([0,0]),this._scale=u.vec2([1,1]),this._rotate=u.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),p.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 ti({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,s;0===this._translate[0]&&0===this._translate[1]||(t=u.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=u.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?u.mulMat4(t,s):s),0!==this._rotate&&(s=u.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?u.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=ri(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 s=new Image;s.onload=function(){s=ri(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.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(),p.memory.textures--}}const li=p.memory,hi=u.AABB3();class ci extends Et{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ke({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=u.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=bt.getPositionsBounds(t.positions),o=bt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new De(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),li.positions+=s.positionsBuf.numItems,u.positions3ToAABB3(t.positions,this._aabb),u.positions3ToAABB3(r,hi,s.positionsDecodeMatrix),u.AABB3ToOBB3(hi,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new De(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),li.colors+=s.colorsBuf.numItems}if(t.uv){const e=bt.getUVBounds(t.uv),r=bt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new De(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),li.uvs+=s.uvBuf.numItems}if(t.normals){const e=bt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new De(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),li.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),li.indices+=s.indicesBuf.numItems;const o=gt(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),li.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(),li.meshes--}}var Ai={};function ui(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,E=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,b,D,N=0,C=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],p=[],d=[];let f,m,E,g,v,I,_,T,R,P,b,D;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),E=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(E+a),c.push(g+l),c.push(v+h),p.push(1-_/i),p.push(T/r),I=u.normalizeVec3(u.subVec3([E,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,b=(i+1)*(T-1)+_,D=(i+1)*T+_,d.push(R),d.push(P),d.push(b),d.push(b),d.push(D),d.push(R);return y.apply(e,{positions:c,normals:A,uv:p,indices:d})}Ai.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Ai.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Ai.parse._buffToStr(e));window.location.href=s},Ai.clone=function(e){return JSON.parse(JSON.stringify(e))},Ai.bin={},Ai.bin.f=new Float32Array(1),Ai.bin.fb=new Uint8Array(Ai.bin.f.buffer),Ai.bin.rf=function(e,t){for(var s=Ai.bin.f,i=Ai.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},Ai.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Ai.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Ai.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Ai.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Ai.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Ai.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Ai.parse={},Ai.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class di extends N{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=u.vec3(t.pos||[0,0,0]),this._up=u.vec3(t.up||[0,1,0]),this._normal=u.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=u.vec3(),this._rtcPos=u.vec3(),this._imageSize=u.vec2(),this._texture=new ai(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 Js(this,{matrix:u.inverseMat4(u.lookAtMat4v(this._pos,u.subVec3(this._pos,this._normal,u.mat4()),this._up,u.mat4())),children:[this._bitmapMesh=new Us(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Ct(this,ui({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Mt(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]}}class fi extends N{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=u.vec3(),r=k(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),E=Object.entries(y).map((([e,t])=>({color:e,components:t})));o.components.coloring=E;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),o.components.translucency=this._createBCFComponents(t.xrayedObjectIds),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=_i(e.location,mi),s=_i(e.direction,mi);h&&u.negateVec3(s),u.subVec3(t,l),r.yUp&&(t=Ri(t),s=Ri(s)),new Vs(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),s.push(r++),s.push(r++))})),new fi(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=_i(e.location,yi),n=_i(e.normal,Ei),a=_i(e.up,gi),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=Ri(o),n=Ri(n),a=Ri(a)),new di(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==r.spaces_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const o=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=_i(e.perspective_camera.camera_view_point,mi),h=_i(e.perspective_camera.camera_direction,mi),c=_i(e.perspective_camera.camera_up_vector,mi),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=_i(e.orthogonal_camera.camera_view_point,mi),h=_i(e.orthogonal_camera.camera_direction,mi),c=_i(e.orthogonal_camera.camera_up_vector,mi),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),u.subVec3(a,l),r.yUp&&(a=Ri(a),h=Ri(h),c=Ri(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:u.addVec3(a,h,mi)}else h=u.addVec3(a,h,mi);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=u.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function Ii(e){return{x:e[0],y:e[1],z:e[2]}}function _i(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ti(e){return new Float64Array([e[0],-e[2],e[1]])}function Ri(e){return new Float64Array([e[0],e[2],-e[1]])}const Pi=u.vec3(),bi=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class Di extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._targetMarker=new ie(s,t.target),this._originWorld=u.vec3(),this._targetWorld=u.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new oe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new re(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new re(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new re(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new re(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new ne(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new ne(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new ne(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new ne(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(u.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,y=s.unitsInfo[m].abbrev;for(var p=0,d=i.length;p{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=t[0]-5+"px",this._markerDiv.style.marginTop=t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),h=e.entity):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class Oi extends L{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Ci(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.target,i=new Di(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=0)&&(e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),i=!1))}));let o=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{o=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{o=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{o&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class xi{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 s=this._messages[this._locale];if(!s)return null;const i=wi(e,s);return i?t?Mi(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=wi(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=Mi(r,[t]),s&&(r=Mi(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[t];i||(i={},this._eventSubs[t]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function wi(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?Gi._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(u.subVec3(i.eye,i.look,Hi),i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Li),i.look=u.subVec3(Li,Hi,Fi)):this._flyingLook&&(i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Fi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Ui)):this._flyingEyeLookUp&&(i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Li),i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Fi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Ui)),this._projection2){const t="ortho"===this._projection2?Gi._easeOutExpo(e,0,1,1):Gi._easeInCubic(e,0,1,1);i.customProjection.matrix=u.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();b.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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=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 ki extends N{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Gi(this),this._t=0,this.state=ki.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,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case ki.SCRUBBING:return;case ki.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=ki.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case ki.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=ki.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=ki.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=ki.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=ki.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=ki.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=ki.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=ki.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}ki.STOPPED=0,ki.SCRUBBING=1,ki.PLAYING=2,ki.PLAYING_TO=3,u.vec3(),u.vec3(),u.vec3(),u.vec3([0,-1,0]),u.vec4([0,0,0,1]);const Vi=u.vec3();class ji{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,s){this.numObjects=0,this._mask=s?y.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,h=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;$i[0]=s,$i[1]=i,$i[2]=t.blendCutoff,$i[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,$i),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===Zi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Zi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Zi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?Ji:qi)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class rr extends ir{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class or extends rr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class nr extends ir{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class ar extends nr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class lr extends ir{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class hr extends ir{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class cr extends ir{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class Ar extends ir{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class ur extends rr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class pr extends rr{_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,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles 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;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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 = 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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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("outColor = vColor;"),o.push("}"),o}}class fr extends or{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class mr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class yr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = vPickColor; "),i.push("}"),i}}class Er extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class gr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),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(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class vr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),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;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Ir extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class _r extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Tr extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),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); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Rr extends rr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&(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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),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(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals 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;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" 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(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class br extends rr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture 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;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),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("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(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("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}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;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e5e6&&(e=5e6),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 Or=u.mat4(),Sr=u.mat4();function xr(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,p=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function Br(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const Fr=u.vec3(),Lr=u.vec3(),Ur=u.vec3(),Hr=u.vec3(),Gr=u.mat4();class kr extends ir{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Fr;let m,y;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=Lr;if(l){const e=Ur;u.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=H(d,t,Gr),y=Hr,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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()}_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,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${u.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Vr=u.vec3(),jr=u.vec3(),Qr=u.vec3(),Wr=u.vec3(),zr=u.mat4();class Kr extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Vr;let m,y;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=jr;if(l){const e=Qr;u.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=H(d,t,zr),y=Wr,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_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 s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Yr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new kr(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new Kr(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new kr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Kr(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Xr={};const Zr=u.mat4(),qr=u.mat4(),Jr=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.OBB3();const $r=u.vec3(),eo=u.vec3(),to=u.vec3(),so=u.vec3(),io=u.vec3(),ro=u.vec3(),oo=u.vec3();class no{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._batchingRenderers=function(e){const t=e.id;let s=Nr[t];return s||(s=new Dr(e),Nr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Nr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=Xr[t];return s||(s=new Yr(e),Xr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Xr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Cr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ke({origin:u.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=u.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=u.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=u.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=u.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Zr;y?u.inverseMat4(u.transposeMat4(y,qr),e):u.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,p=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=Mr(d,"floor","ceil"),a=Br(n),h=o(d,a),h>c&&(l=n,c=h),n=Mr(d,"ceil","ceil"),a=Br(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,r,r.length,v.normals,v.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):xr(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=u.mat4());if(e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new De(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new De(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=bt.getUVBounds(s.uv),r=bt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=u.mat3(r.decodeMatrix),e.uvBuf=new De(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new De(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,i,s.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,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;eE)&&(E=e,i.set(g),r&&u.triangleNormal(d,f,m,r),y=!0)}}return y&&r&&(u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),y}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 ao extends nr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class lo extends nr{_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,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,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,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// 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 vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class co extends ar{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Ao extends ar{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class uo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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("outColor = vPickColor; "),i.push("}"),i}}class po extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class fo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),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(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class mo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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),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;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class yo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 Eo extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),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,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class go extends nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const vo={3e3:"linearToLinear",3001:"sRGBToLinear"};class Io extends nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&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("}"),i.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 = "+vo[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+vo[i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),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(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" 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(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class To extends nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),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 mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.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 );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(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;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${u.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xo=u.vec3(),wo=u.vec3(),Mo=u.vec3(),Bo=u.vec3(),Fo=u.mat4();class Lo extends ir{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=xo;let m,y;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=wo;if(l){const e=u.transformPoint3(c,l,Mo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=H(d,t,Fo),y=Bo,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(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.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_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,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Uo{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new So(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new Lo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new So(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Lo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Ho={};const Go=new Uint8Array(4),ko=new Float32Array(1),Vo=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]);const jo=new Float32Array(3),Qo=u.vec3(),Wo=u.vec3(),zo=u.vec3(),Ko=u.vec3(),Yo=u.vec3(),Xo=u.vec3(),Zo=u.vec3(),qo=new Float32Array(4);class Jo{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Po[t];return s||(s=new Ro(e),Po[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Po[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=Ho[t];return s||(s=new Uo(e),Ho[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ho[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new Ke({numInstances:0,obb:u.OBB3(),origin:u.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=u.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new De(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new De(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new De(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new De(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=u.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new De(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new De(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new De(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new De(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new De(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(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,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Go[0]=t[0],Go[1]=t[1],Go[2]=t[2],Go[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Go,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&j),r=!!(t&Y),o=!!(t&X),n=!!(t&Z),a=!!(t&q),l=!!(t&W),h=!!(t&Q);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Zi.NOT_RENDERED:s?Zi.COLOR_TRANSPARENT:Zi.COLOR_OPAQUE,A=!i||h?Zi.NOT_RENDERED:n?Zi.SILHOUETTE_SELECTED:o?Zi.SILHOUETTE_HIGHLIGHTED:r?Zi.SILHOUETTE_XRAYED:Zi.NOT_RENDERED;let u=0;u=!i||h?Zi.NOT_RENDERED:n?Zi.EDGES_SELECTED:o?Zi.EDGES_HIGHLIGHTED:r?Zi.EDGES_XRAYED:a?s?Zi.EDGES_COLOR_TRANSPARENT:Zi.EDGES_COLOR_OPAQUE:Zi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Zi.PICK:Zi.NOT_RENDERED)<<12,p|=(t&z?1:0)<<16,ko[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(ko,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(jo[0]=t[0],jo[1]=t[1],jo[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(jo,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=Vo,p=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&u.triangleNormal(f,m,y,r),E=!0)}}return E&&r&&(u.transformVec3(a.normalMatrix,r,r),u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),E}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 $o extends cr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class en extends cr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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;"),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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class tn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new $o(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new en(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const sn={};class rn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.OBB3();class on{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=sn[t];return s||(s=new tn(e),sn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete sn[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new rn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ke({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=u.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=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=xr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 an extends Ar{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),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 = 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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class ln{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new an(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const hn={};const cn=new Uint8Array(4),An=new Float32Array(1);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]);const un=new Float32Array(3),pn=new Float32Array(4);class dn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=hn[t];return s||(s=new ln(e),hn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete hn[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new Ke({obb:u.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=u.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=u.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(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,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";cn[0]=t[0],cn[1]=t[1],cn[2]=t[2],cn[3]=t[3],this._state.colorsBuf.setData(cn,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&j),r=!!(t&Y),o=!!(t&X),n=!!(t&Z),a=!!(t&q),l=!!(t&W),h=!!(t&Q);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Zi.NOT_RENDERED:s?Zi.COLOR_TRANSPARENT:Zi.COLOR_OPAQUE,A=!i||h?Zi.NOT_RENDERED:n?Zi.SILHOUETTE_SELECTED:o?Zi.SILHOUETTE_HIGHLIGHTED:r?Zi.SILHOUETTE_XRAYED:Zi.NOT_RENDERED;let u=0;u=!i||h?Zi.NOT_RENDERED:n?Zi.EDGES_SELECTED:o?Zi.EDGES_HIGHLIGHTED:r?Zi.EDGES_XRAYED:a?s?Zi.EDGES_COLOR_TRANSPARENT:Zi.EDGES_COLOR_OPAQUE:Zi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Zi.PICK:Zi.NOT_RENDERED)<<12,p|=(t&z?255:0)<<16,An[0]=p,this._state.flagsBuf.setData(An,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(un[0]=t[0],un[1]=t[1],un[2]=t[2],this._state.offsetsBuf.setData(un,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;pn[0]=t[0],pn[1]=t[4],pn[2]=t[8],pn[3]=t[12],this._state.modelMatrixCol0Buf.setData(pn,s),pn[0]=t[1],pn[1]=t[5],pn[2]=t[9],pn[3]=t[13],this._state.modelMatrixCol1Buf.setData(pn,s),pn[0]=t[2],pn[1]=t[6],pn[2]=t[10],pn[3]=t[14],this._state.modelMatrixCol2Buf.setData(pn,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}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 fn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class mn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 yn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class En extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class gn extends lr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class vn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new fn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new mn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new yn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new En(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new gn(this._scene)),this._occlusionRenderer}_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()}}const In={};class _n{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}u.vec4(),u.vec4(),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.OBB3();class Tn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=In[t];return s||(s=new vn(e),In[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete In[t],s._destroy()}))),s}(e.model.scene),this._buffer=new _n(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ke({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=u.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=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=xr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Pn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class bn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class Dn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Nn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Cn extends hr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 On extends hr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Sn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Rn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Cn(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new bn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Dn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Nn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new On(this._scene)),this._shadowRenderer}_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()}}const xn={};const wn=new Uint8Array(4),Mn=new Float32Array(1);u.vec4([0,0,0,1]),u.vec4([0,0,0,1]),u.vec4([0,0,0,1]);const Bn=new Float32Array(3),Fn=new Float32Array(4);class Ln{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=xn[t];return s||(s=new Sn(e),xn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete xn[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new Ke({obb:u.OBB3(),numInstances:0,origin:e.origin?u.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=u.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){u.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let i=!1;s.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new De(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=u.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new De(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new De(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;s.pickColorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&j&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&X&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Y&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Z&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&z&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&W&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&Y?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&z?(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,s){if(!this._finalized)throw"Not finalized";t&W?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";wn[0]=t[0],wn[1]=t[1],wn[2]=t[2],this._state.colorsBuf.setData(wn,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&j),r=!!(t&Y),o=!!(t&X),n=!!(t&Z),a=!!(t&q),l=!!(t&W),h=!!(t&Q);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Zi.NOT_RENDERED:s?Zi.COLOR_TRANSPARENT:Zi.COLOR_OPAQUE,A=!i||h?Zi.NOT_RENDERED:n?Zi.SILHOUETTE_SELECTED:o?Zi.SILHOUETTE_HIGHLIGHTED:r?Zi.SILHOUETTE_XRAYED:Zi.NOT_RENDERED;let u=0;u=!i||h?Zi.NOT_RENDERED:n?Zi.EDGES_SELECTED:o?Zi.EDGES_HIGHLIGHTED:r?Zi.EDGES_XRAYED:a?s?Zi.EDGES_COLOR_TRANSPARENT:Zi.EDGES_COLOR_OPAQUE:Zi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Zi.PICK:Zi.NOT_RENDERED)<<12,p|=(t&z?255:0)<<16,Mn[0]=p,this._state.flagsBuf.setData(Mn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Bn[0]=t[0],Bn[1]=t[1],Bn[2]=t[2],this._state.offsetsBuf.setData(Bn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;Fn[0]=t[0],Fn[1]=t[4],Fn[2]=t[8],Fn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Fn,s),Fn[0]=t[1],Fn[1]=t[5],Fn[2]=t[9],Fn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Fn,s),Fn[0]=t[2],Fn[1]=t[6],Fn[2]=t[10],Fn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Fn,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Zi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Zi.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._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,Zi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,Zi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,Zi.PICK)}drawPickNormals(e,t){}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()}}class Un{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class Hn{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Gn={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={}}};const kn=new class{constructor(e,t,s){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=s}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,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==Vn[e])return void Vn[e].push({onLoad:t,onProgress:s,onError:i});Vn[e]=[],Vn[e].push({onLoad:t,onProgress:s,onError:i});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 s=Vn[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.length;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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Gn.add(e,t);const s=Vn[e];delete Vn[e];for(let e=0,i=s.length;e{const s=Vn[e];if(void 0===s)throw this.manager.itemError(e),t;delete Vn[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Qn{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{const i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Wn=0;class zn{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Qn,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new jn;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new jn;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=zn.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(zn.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(zn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(zn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),Wn>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Wn++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===A?3001:3e3,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Wn--}}zn.BasisFormat={ETC1S:0,UASTC_4x4:1},zn.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},zn.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},zn.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),y=n.getDFDFlags(),{transcoderFormat:E,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const s=this._getNextId(),n=new i(s);for(let s=0,i=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new o(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(r);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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("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;ewindow.innerHeight&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}let a=!0,l=a?Float64Array:Float32Array;const h=new l(3),c=new l(16),A=new l(16),u=new l(4),p={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 s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+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){},doublesToFloats(e,t,s){const i=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new l(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>p.dotVec4(e,e),lenVec4:e=>Math.sqrt(p.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=>p.dotVec3(e,e),sqLenVec2:e=>p.dotVec2(e,e),lenVec3:e=>Math.sqrt(p.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,s)=>p.lenVec3(p.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(p.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,s)=>p.lenVec2(p.subVec2(t,s,e))})(),rcpVec3:(e,t)=>p.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/p.lenVec4(e);return p.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/p.lenVec3(e);return p.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/p.lenVec2(e);return p.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=p.dotVec3(e,t)/Math.sqrt(p.sqLenVec3(e)*p.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=p.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=p.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=p.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||p.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:()=>p.m4s(0),setMat4ToOnes:()=>p.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,s,i)=>p.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>p.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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>p.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],y=e[14],E=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],b=t[7],D=t[8],N=t[9],C=t[10],O=t[11],S=t[12],x=t[13],w=t[14],M=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*y,s[3]=g*n+v*c+I*d+_*E,s[4]=T*i+R*a+P*A+b*f,s[5]=T*r+R*l+P*u+b*m,s[6]=T*o+R*h+P*p+b*y,s[7]=T*n+R*c+P*d+b*E,s[8]=D*i+N*a+C*A+O*f,s[9]=D*r+N*l+C*u+O*m,s[10]=D*o+N*h+C*p+O*y,s[11]=D*n+N*c+C*d+O*E,s[12]=S*i+x*a+w*A+M*f,s[13]=S*r+x*l+w*u+M*m,s[14]=S*o+x*h+w*p+M*y,s[15]=S*n+x*c+w*d+M*E,s},mulMat3(e,t,s){s||(s=new l(9));const i=e[0],r=e[3],o=e[6],n=e[1],a=e[4],h=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],y=t[4],E=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*y+o*v,s[6]=i*f+r*E+o*I,s[1]=n*p+a*m+h*g,s[4]=n*d+a*y+h*v,s[7]=n*f+a*E+h*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*y+u*v,s[8]=c*f+A*E+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=p.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],y=e[15],E=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,b=c*y-p*d,D=A*m-u*f,N=A*y-p*f,C=u*y-p*m,O=1/(E*C-g*N+v*D+I*b-_*P+T*R);return t[0]=(a*C-l*N+h*D)*O,t[1]=(-i*C+r*N-o*D)*O,t[2]=(f*T-m*_+y*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*C+l*b-h*P)*O,t[5]=(s*C-r*b+o*P)*O,t[6]=(-d*T+m*v-y*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*N-a*b+h*R)*O,t[9]=(-s*N+i*b-o*R)*O,t[10]=(d*_-f*v+y*E)*O,t[11]=(-c*_+A*v-p*E)*O,t[12]=(-n*D+a*P-l*R)*O,t[13]=(s*D-i*P+r*R)*O,t[14]=(-d*I+f*g-m*E)*O,t[15]=(c*I-A*g+u*E)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||p.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||p.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.translationMat4v(e,r))})(),translationMat4s:(e,t)=>p.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>p.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=p.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,u,d,f,m;return c=a*l,A=l*h,u=h*a,d=a*r,f=l*r,m=h*r,(s=s||p.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*u-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*u+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>p.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=p.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=p.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>p.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=p.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,u=i*h,d=r*l,f=r*h,m=o*h,y=n*a,E=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=u-E,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+y,s[7]=0,s[8]=u+E,s[9]=f-y,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=p.vec4()){const i=p.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],u=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,u),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,u),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,u),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,u),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,u))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,u),s[1]=0)),s},composeMat4:(e,t,s,i=p.mat4())=>(p.quaternionToRotationMat4(t,i),p.scaleMat4v(s,i),p.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=p.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=p.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=p.lenVec3(e);p.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,p.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=p.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],u=t[2];if(r===c&&o===A&&n===u)return p.identityMat4();let d,f,m,y,E,g,v,I,_,T;return d=r-c,f=o-A,m=n-u,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,y=l*m-h*f,E=h*d-a*m,g=a*f-l*d,T=Math.sqrt(y*y+E*E+g*g),T?(T=1/T,y*=T,E*=T,g*=T):(y=0,E=0,g=0),v=f*g-m*E,I=m*y-d*g,_=d*E-f*y,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=y,i[1]=v,i[2]=d,i[3]=0,i[4]=E,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(y*r+E*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>p.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=p.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];p.addVec4(r,i,c),p.subVec4(r,i,A);const o=2*i[2],n=A[0],a=A[1],l=A[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=c[0]/n,s[9]=c[1]/a,s[10]=-c[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],p.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,s=p.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=p.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],y=e[8],E=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),s=new l(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||p.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||p.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=p.vec4()){const i=e[0]*p.DEGTORAD/2,r=e[1]*p.DEGTORAD/2,o=e[2]*p.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=p.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const u=s+n+c;return u>0?(A=.5/Math.sqrt(u+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=p.vec4()){const i=Math.sqrt(p.dotVec3(e,e)*p.dotVec3(t,t));let r=i+p.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):p.cross3Vec3(e,t,s),s[3]=r,p.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=p.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new l(16);return(t,s,i)=>(i=i||p.vec3(),p.quaternionToRotationMat4(t,e),p.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=p.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=p.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,u=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-u*-a,s[1]=A*h+d*-a+u*-n-c*-l,s[2]=u*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=p.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,u=n*s,d=a*s,f=l*s,m=a*i,y=l*i,E=l*r;return t[0]=1-(m+E),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(u+E),t[6]=y+h,t[8]=f+c,t[9]=y-h,t[10]=1-(u+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,y=o*l;return t[0]=1-(u+d),t[4]=c-y,t[8]=A+m,t[1]=c+y,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+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 s=p.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,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)=>p.normalizeQuaternion(p.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=p.vec4()){const s=(e=p.normalizeQuaternion(e,u))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,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,s,i)=>new l([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],y=e[9],E=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new l(3),t=new l(3),s=new l(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],p.subVec3(t,e,s),Math.abs(p.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=p.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(p.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||p.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||p.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=p.AABB3())=>(e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MAX_DOUBLE,e[3]=p.MIN_DOUBLE,e[4]=p.MIN_DOUBLE,e[5]=p.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=p.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,s,i)=>{s=s||p.AABB3();let r,o,n,a=p.MAX_DOUBLE,l=p.MAX_DOUBLE,h=p.MAX_DOUBLE,c=p.MIN_DOUBLE,A=p.MIN_DOUBLE,u=p.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>u&&(u=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=u,s}})(),OBB3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new l(3);return(t,s)=>{s=s||p.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=p.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=p.vec3()){let s=0,i=0,r=0;for(var o=0,n=e.length;o(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](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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MIN_DOUBLE,e[3]=p.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=p.AABB2()){let s,i,r,o,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=p.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,u=r*l-o*a,d=Math.sqrt(c*c+A*A+u*u);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=u/d),i},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3);return(o,n,a,l,h,c)=>{c=c||p.vec3();const A=p.subVec3(l,a,e),u=p.subVec3(h,a,t),d=p.cross3Vec3(n,u,s),f=p.dotVec3(A,d);if(f<1e-6)return null;const m=p.subVec3(o,a,i),y=p.dotVec3(m,d);if(y<0||y>f)return null;const E=p.cross3Vec3(m,A,r),g=p.dotVec3(n,E);if(g<0||y+g>f)return null;const v=p.dotVec3(u,E)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3);return(r,o,n,a,l,h)=>{h=h||p.vec3(),o=p.normalizeVec3(o,e);const c=p.subVec3(a,n,t),A=p.subVec3(l,n,s),u=p.cross3Vec3(c,A,i);p.normalizeVec3(u,u);const d=-p.dotVec3(n,u),f=-(p.dotVec3(r,u)+d)/p.dotVec3(o,u);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r,o,n,a)=>{const l=p.subVec3(n,r,e),h=p.subVec3(o,r,t),c=p.subVec3(i,r,s),A=p.dotVec3(l,l),u=p.dotVec3(l,h),d=p.dotVec3(l,c),f=p.dotVec3(h,h),m=p.dotVec3(h,c),y=A*f-u*u;if(0===y)return null;const E=1/y,g=(f*d-u*m)*E,v=(A*m-u*d)*E;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=p.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,y=0;for(f=0,m=e.length;f{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let u,d,f,m,y,E,g;for(h=0,c=a.length;h{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const u=1e4;let d,f,m,y,E,g;for(f=0,y=e.length;f{const e=new l(4),t=new l(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,p.transformVec4(s,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],p.transformVec3(s,e,t),p.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),s=new l(4),i=new l(4),r=new l(4),o=new l(4);return(n,a,l,h,c,A)=>{const u=p.mulMat4(l,a,e),d=p.inverseMat4(u,t),f=n.width,m=n.height,y=(h[0]-f/2)/(f/2),E=-(h[1]-m/2)/(m/2);s[0]=y,s[1]=E,s[2]=-1,s[3]=1,p.transformVec4(d,s,i),p.mulVec4Scalar(i,1/i[3]),r[0]=y,r[1]=E,r[2]=1,r[3]=1,p.transformVec4(d,r,o),p.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],p.subVec3(o,i,A),p.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(s,i,r,o,n,a,l)=>{p.canvasPosToWorldRay(s,i,r,n,e,t),p.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),s=new l(4);return(i,r,o,n,a)=>{const l=p.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,p.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],p.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let h,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,h=0,c=s.length;hn[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(s.length<20||o>10)return a.triangles=s,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 p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let y=0;for(h=0,c=s.length;h{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};p.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}(),p.planeClipsPositions3=function(e,t,s,i=3){for(let r=0,o=s.length;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;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),s=new Uint8Array(e);for(var n=0;n=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}},_={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let R,P=0,b=0;const D=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(D.scenes[e.id])return void console.error(`[ERROR] Scene ${E.inQuotes(e.id)} already exists`)}else e.id=v.addItem({});D.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;g[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{v.removeItem(e.id),delete D.scenes[e.id],delete g[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in D.scenes)D.scenes.hasOwnProperty(t)&&(e=D.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete D.scenes[e.id]))},this.scheduleTask=function(e,t){I.push(e),I.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;I.length>0&&(e<0||i0&&R>0){var t=1e3/R;b+=t,T.push(t),T.length>=30&&(b-=T.shift()),d.frame.fps=Math.round(b/T.length)}!function(e){const t=D.runTasks(e+10),s=D.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in _.time=e,D.scenes)if(D.scenes.hasOwnProperty(t)){var s=D.scenes[t];_.sceneId=t,_.startTime=s.startTime,_.deltaTime=null!=_.prevTime?_.time-_.prevTime:0,s.fire("tick",_,!0)}_.prevTime=e}(e),function(){const e=D.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=g[n],i||(i=g[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),P=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(N):requestAnimationFrame(N)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(N):requestAnimationFrame(N);class C{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 C))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,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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+" "+E.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 s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(E.isNumeric(s)||E.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+E.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+E.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+E.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():D.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_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,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class M{constructor(){this.planes=[new w,new w,new w,new w,new w,new w]}}function B(e,t,s){const i=p.mulMat4(s,t,x),r=i[0],o=i[1],n=i[2],a=i[3],l=i[4],h=i[5],c=i[6],A=i[7],u=i[8],d=i[9],f=i[10],m=i[11],y=i[12],E=i[13],g=i[14],v=i[15];e.planes[0].set(a-r,A-l,m-u,v-y),e.planes[1].set(a+r,A+l,m+u,v+y),e.planes[2].set(a-o,A-h,m-d,v-E),e.planes[3].set(a+o,A+h,m+d,v+E),e.planes[4].set(a-n,A-c,m-f,v-g),e.planes[5].set(a+n,A+c,m+f,v+g)}function F(e,t){let s=M.INSIDE;const i=O,r=S;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return M.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=M.INTERSECT)}return s}M.INSIDE=0,M.INTERSECT=1,M.OUTSIDE=2;class L extends C{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=p.vec2(),this._canvasMarqueeCorner2=p.vec2(),this._canvasMarquee=p.AABB2(),this._marqueeFrustum=new M,this._marqueeFrustumProjMat=p.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!==L.PICK_MODE_INSIDE&&e!==L.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===L.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=(s,i=M.INTERSECT)=>{if(i===M.INTERSECT&&(i=F(this._marqueeFrustum,s.aabb)),i!==M.OUTSIDE){if(s.entities){const t=s.entities;for(let s=0,i=t.length;s3||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,s=e.clientHeight,i=e.clientLeft,r=e.clientTop,o=2/t,n=2/s,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-i)*o-1,h=(this._canvasMarquee[2]-i)*o-1,c=-(this._canvasMarquee[3]-r)*n+1,A=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);p.frustumMat4(l,h,c*a,A*a,u,1e4,this._marqueeFrustumProjMat),B(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)}}L.PICK_MODE_INTERSECTS=0,L.PICK_MODE_INSIDE=1;class U{constructor(e,t,s){this.id=s&&s.id?s.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)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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)}}const H=p.vec3(),G=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(i,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,p.transformVec4(i,t,s),p.setMat4Translation(i,s,o),o.slice()}}();function k(e,t,s){const i=Float32Array.from([e[0]])[0],r=e[0]-i,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=i,t[1]=o,t[2]=a,s[0]=r,s[1]=n,s[2]=l}function V(e,t,s,i=1e3){const r=p.getPositionsCenter(e,H),o=Math.round(r[0]/i)*i,n=Math.round(r[1]/i)*i,a=Math.round(r[2]/i)*i;s[0]=o,s[1]=n,s[2]=a;const l=0!==s[0]||0!==s[1]||0!==s[2];if(l)for(let s=0,i=e.length;s0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(p.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){se.set(this._viewPos),se[3]=1,p.transformPoint4(this.scene.camera.projMatrix,se,ie);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ie[0]/ie[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ie[1]/ie[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){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof te?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)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),k(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._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class oe{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class ne{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!0,this._culled=!1;var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ae{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var le=p.vec3(),he=p.vec3();class ce extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new re(s,t.origin),this._cornerMarker=new re(s,t.corner),this._targetMarker=new re(s,t.target),this._originWorld=p.vec3(),this._cornerWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new oe(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new oe(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new ae(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>u||f>u||m>u)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const y=this._container.getBoundingClientRect();for(var r=i.top-y.top,o=i.left-y.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const s=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),h.set(s),this._mouseState){case 0:this.markerDiv.style.marginLeft=s[0]-5+"px",this.markerDiv.style.marginTop=s[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,i&&(i.visible=!0,i.pointerPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class pe extends U{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new ue(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.corner,i=e.target,r=new ce(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t
',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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.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 s=this._element;s&&(s.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 fe=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class me extends C{constructor(e,t={}){super(e,t),this._backgroundColor=p.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 s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new de(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-"+p.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Ee.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Ee.FS_MAX_FLOAT_PRECISION="mediump":Ee.FS_MAX_FLOAT_PRECISION="lowp":Ee.FS_MAX_FLOAT_PRECISION="mediump",Ee.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Ee.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Ee.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Ee.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Ee.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ee.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Ee.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Ee.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Ee.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Ee.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Ee.SUPPORTED_EXTENSIONS[e]=!0})))}class ve{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}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}}class Ie{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function be(e){console.error(e.join("\n"))}class De{constructor(e,t){this.id=Re.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 Ie(e,e.VERTEX_SHADER,Pe(this.source.vertex)),this._fragmentShader=new Ie(e,e.FRAGMENT_SHADER,Pe(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void be(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void be(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void be(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void be(this.errors);let t,s,i,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 be(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ce{constructor(e,t){this.scene=e,this.aabb=p.AABB3(),this.origin=p.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-t){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{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 s=this._occlusionLayers[t];s||(s=new Ce(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ce(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.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;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new De(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),u=Math.random(),d="perspective"===i.camera.projection;we[0]=o,we[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,we),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();s.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)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new De(s,{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 i=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 Ne(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new Ne(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new Ne(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.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 Be=new Float32Array(ke(17,[0,1])),Fe=new Float32Array(ke(17,[1,0])),Le=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(Ge(i,t));return s}(17,4)),Ue=new Float32Array(2);class He{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 De(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]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Ne(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new Ne(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Ne(e,e.ELEMENT_ARRAY_BUFFER,i,i.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,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Ue[0]=n,Ue[1]=a,i.uniform2fv(this._uViewport,Ue),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Fe):i.uniform2fv(this._uSampleOffsets,Be),i.uniform1fv(this._uSampleWeights,Le);const A=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Ge(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ke(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class Ve{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.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,s=null){const i=this.gl,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),s?i.texStorage2D(i.TEXTURE_2D,1,s,e,t):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),r}_touch(...e){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;this.buffer.textures.forEach((e=>i.deleteTexture(e))),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,s,e)))):r.push(this.createTexture(t,s)),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();i.bindFramebuffer(i.FRAMEBUFFER,a);for(let e=0;e0&&i.drawBuffers(r.map(((e,t)=>i.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.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:s},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,s=null,i=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,h=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,s||c.RGBA,i||c.UNSIGNED_BYTE,h,0),h}readArray(e=null,t=null,s=Uint8Array,i=4,r=0){const o=new s(this.buffer.width*this.buffer.height*i),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(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;ee.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 je{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let i=s[e];return i||(i=new Ve(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=i),i}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Qe(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=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":s=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":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}const We=function(e,s){s=s||{};const i=new ye(e),r=e.canvas.canvas,o=e.canvas.gl,n=!!s.transparent,a=s.alphaDepthMask,l=new t({});let h={},c={},A=!0,u=!0,f=!0,m=!0,y=!0,E=!0,g=!0,v=!0;const I=new je(e);let _=!1;const T=new Me(e),R=new He(e);function P(){A&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableMap,i=t.drawableListPreCull;let r=0;for(let e in s)s.hasOwnProperty(e)&&(i[r++]=s[e]);i.length=r}}(),A=!1,u=!0),u&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),u=!1,f=!0),f&&function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableListPreCull,i=t.drawableList;let r=0;for(let e=0,t=s.length;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.lastProgramId=null,e.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.lastProgramId=null,e.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=u.size[0],i=t%s-Math.floor(s/2),r=Math.floor(t/s)-Math.floor(s/2),o=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));D.push({x:i,y:r,dist:o,isVertex:n&&a?E[e+3]>y.length/2:n,result:[E[e+0],E[e+1],E[e+2],E[e+3]],normal:[g[e+0],g[e+1],g[e+2],g[e+3]],id:[v[e+0],v[e+1],v[e+2],v[e+3]]})}let S=null,x=null,w=null,M=null;if(D.length>0){D.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),M=D[0].isVertex?"vertex":"edge";const e=D[0].result,t=D[0].normal,s=D[0].id,i=y[e[3]],r=i.origin,o=i.coordinateScale;x=p.normalizeVec3([t[0]/p.MAX_INT,t[1]/p.MAX_INT,t[2]/p.MAX_INT]),S=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],w=l.items[s[0]+(s[1]<<8)+(s[2]<<16)+(s[3]<<24)]}if(null===_&&null==S)return null;let B=null;null!==S&&(B=e.camera.projectWorldPos(S));const F=w&&w.delegatePickedEntity?w.delegatePickedEntity():w;return c.reset(),c.snappedToEdge="edge"===M,c.snappedToVertex="vertex"===M,c.worldPos=S,c.worldNormal=x,c.entity=F,c.canvasPos=s,c.snappedCanvasPos=B||s,c}}(),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new xe(e,I),this._occlusionTester.addMarker(t),e.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){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.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 in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=t.length;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())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,s)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));t(i)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!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("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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()}}const Ke=new t({});class Ye{constructor(e){this.id=Ke.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){Ke.removeItem(this.id)}}class Xe extends C{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Ye({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],s=e[3];this._state.boundary=[0,0,t,s],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 Ze extends C{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),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],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),p.perspectiveMat4(i*(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:2e3;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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class qe extends C{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),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,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),p.orthoMat4c(n,a,h,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:2e3;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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class Je extends C{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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(){p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class $e extends C{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const et=p.vec3(),tt=p.vec3(),st=p.vec3(),it=p.vec3(),rt=p.vec3(),ot=p.vec3(),nt=p.vec4(),at=p.vec4(),lt=p.vec4(),ht=p.mat4(),ct=p.mat4(),At=p.vec3(),ut=p.vec3(),pt=p.vec3(),dt=p.vec3();class ft extends C{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Ye({deviceMatrix:p.mat4(),hasDeviceMatrix:!1,matrix:p.mat4(),normalMatrix:p.mat4(),inverseMatrix:p.mat4()}),this._perspective=new Ze(this),this._ortho=new qe(this),this._frustum=new Je(this),this._customProjection=new $e(this),this._project=this._perspective,this._eye=p.vec3([0,0,10]),this._look=p.vec3([0,0,0]),this._up=p.vec3([0,1,0]),this._worldUp=p.vec3([0,1,0]),this._worldRight=p.vec3([1,0,0]),this._worldForward=p.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?(p.subVec3(this._eye,this._look,At),p.normalizeVec3(At,ut),p.mulVec3Scalar(ut,1e3,pt),p.addVec3(this._look,pt,dt),t=dt):t=this._eye,e.hasDeviceMatrix?(p.lookAtMat4v(t,this._look,this._up,ct),p.mulMat4(e.deviceMatrix,ct,e.matrix)):p.lookAtMat4v(t,this._look,this._up,e.matrix),p.inverseMat4(this._state.matrix,this._state.inverseMatrix),p.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=p.subVec3(this._eye,this._look,et);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ht),t=p.transformPoint3(ht,t,tt),this.eye=p.addVec3(this._look,t,st),this.up=p.transformPoint3(ht,this._up,it)}orbitPitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._eye,this._look,et);const s=p.cross3Vec3(p.normalizeVec3(t,tt),p.normalizeVec3(this._up,st));p.rotationMat4v(.0174532925*e,s,ht),t=p.transformPoint3(ht,t,it),this.up=p.transformPoint3(ht,this._up,rt),this.eye=p.addVec3(t,this._look,ot)}yaw(e){let t=p.subVec3(this._look,this._eye,et);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ht),t=p.transformPoint3(ht,t,tt),this.look=p.addVec3(t,this._eye,st),this._gimbalLock&&(this.up=p.transformPoint3(ht,this._up,it))}pitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._look,this._eye,et);const s=p.cross3Vec3(p.normalizeVec3(t,tt),p.normalizeVec3(this._up,st));p.rotationMat4v(.0174532925*e,s,ht),this.up=p.transformPoint3(ht,this._up,ot),t=p.transformPoint3(ht,t,it),this.look=p.addVec3(t,this._eye,rt)}pan(e){const t=p.subVec3(this._eye,this._look,et),s=[0,0,0];let i;if(0!==e[0]){const r=p.cross3Vec3(p.normalizeVec3(t,[]),p.normalizeVec3(this._up,tt));i=p.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=p.mulVec3Scalar(p.normalizeVec3(this._up,st),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=p.mulVec3Scalar(p.normalizeVec3(t,it),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=p.addVec3(this._eye,s,rt),this.look=p.addVec3(this._look,s,ot)}zoom(e){const t=p.subVec3(this._eye,this._look,et),s=Math.abs(p.lenVec3(t,tt)),i=Math.abs(s+e);if(i<.5)return;const r=p.normalizeVec3(t,st);this.eye=p.addVec3(this._look,p.mulVec3Scalar(r,i),it)}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=p.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 p.lenVec3(p.subVec3(this._look,this._eye,et))}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}projectWorldPos(e){const t=nt,s=at,i=lt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,p.mulMat4v4(this.viewMatrix,t,s),p.mulMat4v4(this.projMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class mt extends C{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class yt extends mt{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 s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Ye({type:"dir",dir:p.vec3([1,1,1]),color:p.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=p.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];p.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=p.identityMat4()),p.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Ve(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 Et extends mt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:p.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 gt extends C{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),d.memory.meshes++}destroy(){super.destroy(),d.memory.meshes--}}var vt=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}();const It=function(){const e=p.mat4(),t=p.mat4();return function(s,i){i=i||p.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return p.identityMat4(e),p.translationMat4v(s,e),p.identityMat4(t),p.scalingMat4v([a/c,l/c,h/c],t),p.mulMat4(e,t,i),i}}();var _t=function(){const e=p.mat4(),t=p.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function Pt(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function bt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const Dt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=Rt(e,a,"floor","ceil"),i=Pt(s),o=bt(e,a,i),o>n&&(r=s,n=o),s=Rt(e,a,"ceil","ceil"),i=Pt(s),o=bt(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},Nt=d.memory,Ct=p.AABB3();class Ot extends gt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ye({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 s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Dt.getPositionsBounds(t.positions),i=Dt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Dt.getUVBounds(t.uv),i=Dt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=Dt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.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(),Nt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Nt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Nt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new Ne(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),Nt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Nt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Ne(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Nt.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,s=vt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),Nt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=p.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new Ne(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Nt.positions+=this._pickTrianglePositionsBuf.numItems,Nt.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),Dt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=Dt.getPositionsBounds(e),i=Dt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),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),Dt.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,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),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),Dt.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,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),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,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),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=p.AABB3()),p.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=p.OBB3()),p.positions3ToAABB3(this._state.positions,Ct,this._state.positionsDecodeMatrix),p.AABB3ToOBB3(Ct,this._obb),this._obbDirty=!1),this._obb}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(),Nt.meshes--}}function St(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return E.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,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]})}class xt extends C{get type(){return"Material"}constructor(e,t={}){super(e,t),d.memory.materials++}destroy(){super.destroy(),d.memory.materials--}}const wt={opaque:0,mask:1,blend:2},Mt=["opaque","mask","blend"];class Bt extends xt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Ye({type:"PhongMaterial",ambient:p.vec3([1,1,1]),diffuse:p.vec3([1,1,1]),specular:p.vec3([1,1,1]),emissive:p.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=wt[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 Mt[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()}}const Ft={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 Lt extends xt{get type(){return"EmphasisMaterial"}get presets(){return Ft}constructor(e,t={}){super(e,t),this._state=new Ye({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(e=e||"default",this._preset===e)return;const t=Ft[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(Ft).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Ut={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 Ht extends xt{get type(){return"EdgeMaterial"}get presets(){return Ut}constructor(e,t={}){super(e,t),this._state=new Ye({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=Ut[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(Ut).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Gt={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 kt extends C{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=p.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return Gt}set units(e){e||(e="meters");Gt[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=p.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=p.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 Vt extends C{constructor(e,t={}){super(e,t),this._supported=Ee.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()}}const jt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Qt extends xt{get type(){return"PointsMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new Ye({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=jt[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(jt).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 Wt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class zt extends xt{get type(){return"LinesMaterial"}get presets(){return Wt}constructor(e,t={}){super(e,t),this._state=new Ye({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=Wt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Wt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Kt(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new We(this,{transparent:i,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 s=[];for(let e=0,i=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=p.vec4([0,0,0,0]),t=p.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,i=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let i;for(let s=0,r=t.length;s0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+E.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=p.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[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,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],E.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_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)}_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)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_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)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(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}_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}_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 s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}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}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&D.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 s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=Kt(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=Kt(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}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,s=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=p.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){E.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i{r>i&&(i=r,e(...s))}));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.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.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const Xt=1e3,Zt=1001,qt=1002,Jt=1003,$t=1004,es=1005,ts=1006,ss=1007,is=1008,rs=1008,os=1023,ns=33776,as=33777,ls=33778,hs=33779,cs=35840,As=35842,us=37492,ps=37496,ds=37808,fs=36492,ms=3e3,ys=3001,Es=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,i=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=s.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.lights.length;e0,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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.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),A=Is(e),u=i.getNumAllocatedSectionPlanes()>0,p=vs(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&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;"),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(A){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= 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;"),d&&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] = 1.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] = 1.0;"),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(p){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;e0&&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;e0,l=Is(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=vs(e);t.gammaInput;const d=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;"));p&&(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("}"),d&&(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;m0&&(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 = "+gs[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("}")),(A||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 = "+gs[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._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("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._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("}"),s._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;")),s._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;")),s._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;")),s._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;")),s._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 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._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 = "+gs[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+gs[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+gs[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+gs[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._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)){h&&s._normalMap?(s._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);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._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;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._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);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._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;")),A&&(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||A)&&(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;e0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class bs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 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] = 1.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] = 1.0;"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.lights.length;e0,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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ds=new t({}),Ns=p.vec3(),Cs=function(e,t){this.id=Ds.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new bs(t),this._allocate(t)},Os={};Cs.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 s=Os[t];return s||(s=new Cs(t,e),Os[t]=s,d.memory.programs++),s._useCount++,s},Cs.prototype.put=function(){0==--this._useCount&&(Ds.removeItem(this.id),this._program&&this._program.destroy(),delete Os[this._hash],d.memory.programs--)},Cs.prototype.webglContextRestored=function(){this._program=null},Cs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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] = 1.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] = 1.0;"),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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const xs=new t({}),ws=p.vec3(),Ms=function(e,t){this.id=xs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ss(t),this._allocate(t)},Bs={};Ms.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 s=Bs[t];return s||(s=new Ms(t,e),Bs[t]=s,d.memory.programs++),s._useCount++,s},Ms.prototype.put=function(){0==--this._useCount&&(xs.removeItem(this.id),this._program&&this._program.destroy(),delete Bs[this._hash],d.memory.programs--)},Ms.prototype.webglContextRestored=function(){this._program=null},Ms.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=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=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.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;"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 Ls=p.vec3(),Us=function(e,t){this._hash=e,this._shaderSource=new Fs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Hs={};Us.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Hs[t];if(!s){if(s=new Us(t,e),s.errors)return console.log(s.errors.join("\n")),null;Hs[t]=s,d.memory.programs++}return s._useCount++,s},Us.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Hs[this._hash],d.memory.programs--)},Us.prototype.webglContextRestored=function(){this._program=null},Us.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},Us.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new De(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 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 ks=p.vec3(),Vs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Gs(t),this._allocate(t)},js={};Vs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=js[t];if(!s){if(s=new Vs(t,e),s.errors)return console.log(s.errors.join("\n")),null;js[t]=s,d.memory.programs++}return s._useCount++,s},Vs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete js[this._hash],d.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 Ws=p.vec3(),zs=function(e,t){this._hash=e,this._shaderSource=new Qs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ks={};zs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Ks[t];if(!s){if(s=new zs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ks[t]=s,d.memory.programs++}return s._useCount++,s},zs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ks[this._hash],d.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.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"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Xs=function(e,t){this._hash=e,this._shaderSource=new Ys(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Zs={};Xs.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Zs[s];if(!i){if(i=new Xs(s,e),i.errors)return console.log(i.errors.join("\n")),null;Zs[s]=i,d.memory.programs++}return i._useCount++,i},Xs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Zs[this._hash],d.memory.programs--)},Xs.prototype.webglContextRestored=function(){this._program=null},Xs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Xs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new De(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const hi=function(){const e=p.vec3(),t=p.vec3(),s=p.vec3(),i=p.vec3(),r=p.vec3(),o=p.vec3(),n=p.vec4(),a=p.vec3(),l=p.vec3(),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3(),y=p.vec4(),E=p.vec4(),g=p.vec4(),v=p.vec3(),I=p.vec3(),_=p.vec3(),T=p.vec3(),R=p.vec3(),P=p.vec3(),b=p.vec3(),D=p.vec3(),N=p.vec3(),C=p.vec3(),O=p.vec3();return function(S,x,w,M){var B=M.primIndex;if(null!=B&&B>-1){const H=S.geometry._state,k=S.scene,V=k.camera,j=k.canvas;if("triangles"===H.primitiveName){M.primitive="triangle";const k=B,Q=H.indices,W=H.positions;let z,K,Y;if(Q){var F=Q[k+0],L=Q[k+1],U=Q[k+2];o[0]=F,o[1]=L,o[2]=U,M.indices=o,z=3*F,K=3*L,Y=3*U}else z=3*k,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],H.compressGeometry){const e=H.positionsDecodeMatrix;e&&(Dt.decompressPosition(s,e,s),Dt.decompressPosition(i,e,i),Dt.decompressPosition(r,e,r))}M.canvasPos?p.canvasPosToLocalRay(j.canvas,S.origin?G(x,S.origin):x,w,S.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&p.worldRayToLocalRay(S.worldMatrix,M.origin,M.direction,e,t),p.normalizeVec3(t),p.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,y[0]=n[0],y[1]=n[1],y[2]=n[2],y[3]=1,p.transformVec4(S.worldMatrix,y,E),a[0]=E[0],a[1]=E[1],a[2]=E[2],M.canvasPos&&S.origin&&(a[0]+=S.origin[0],a[1]+=S.origin[1],a[2]+=S.origin[2]),M.worldPos=a,p.transformVec4(V.matrix,E,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,p.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=H.normals;if(X){if(H.compressGeometry){const e=3*F,t=3*L,s=3*U;Dt.decompressNormal(X.subarray(e,e+2),c),Dt.decompressNormal(X.subarray(t,t+2),A),Dt.decompressNormal(X.subarray(s,s+2),u)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],u[0]=X[Y],u[1]=X[Y+1],u[2]=X[Y+2];const e=p.addVec3(p.addVec3(p.mulVec3Scalar(c,h[0],v),p.mulVec3Scalar(A,h[1],I),_),p.mulVec3Scalar(u,h[2],T),R);M.worldNormal=p.normalizeVec3(p.transformVec3(S.worldNormalMatrix,e,P))}const Z=H.uv;if(Z){if(d[0]=Z[2*F],d[1]=Z[2*F+1],f[0]=Z[2*L],f[1]=Z[2*L+1],m[0]=Z[2*U],m[1]=Z[2*U+1],H.compressGeometry){const e=H.uvDecodeMatrix;e&&(Dt.decompressUV(d,e,d),Dt.decompressUV(f,e,f),Dt.decompressUV(m,e,m))}M.uv=p.addVec3(p.addVec3(p.mulVec2Scalar(d,h[0],b),p.mulVec2Scalar(f,h[1],D),N),p.mulVec2Scalar(m,h[2],C),O)}}}}}();function ci(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],y=[],g=[],v=[];let I,_,T,R,P,b,D,N,C,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,b=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),y.push(P*T),y.push(x),y.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(b+h),m.push(P*R+c);for(I=0;I0){for(C=m.length/3,y.push(0),y.push(1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(t*T),y.push(1),y.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(C=m.length/3,y.push(0),y.push(-1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(s*T),y.push(-1),y.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Ti(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=Ti(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Ti(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Di(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Di(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Ti(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Ti(s,this.magFilter)));const a=Ti(s,this.format,this.encoding),l=Ti(s,this.type),h=bi(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class Si extends C{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ye({texture:new Pi({gl:this.scene.canvas.gl}),matrix:p.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=p.vec2([0,0]),this._scale=p.vec2([1,1]),this._rotate=p.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),d.memory.textures++}_checkMinFilter(e){return(e=e||rs)!==ts&&e!==ss&&e!==rs&&e!==es&&e!==$t&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=rs),e}_checkMagFilter(e){return(e=e||ts)!==ts&&e!==Jt&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=ts),e}_checkWrapS(e){return(e=e||Xt)!==Zt&&e!==qt&&e!==Xt&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Xt),e}_checkWrapT(e){return(e=e||Xt)!==Zt&&e!==qt&&e!==Xt&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Xt),e}_checkFlipY(e){return!!e}_checkEncoding(e){return(e=e||ms)!==ms&&e!==ys&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=ms),e}_webglContextRestored(){this._state.texture=new Pi({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,s;0===this._translate[0]&&0===this._translate[1]||(t=p.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=p.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?p.mulMat4(t,s):s),0!==this._rotate&&(s=p.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?p.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Ni(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 s=new Image;s.onload=function(){s=Ni(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.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(),d.memory.textures--}}const xi=d.memory,wi=p.AABB3();class Mi extends gt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ye({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=p.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Dt.getPositionsBounds(t.positions),o=Dt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new Ne(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),xi.positions+=s.positionsBuf.numItems,p.positions3ToAABB3(t.positions,this._aabb),p.positions3ToAABB3(r,wi,s.positionsDecodeMatrix),p.AABB3ToOBB3(wi,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new Ne(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),xi.colors+=s.colorsBuf.numItems}if(t.uv){const e=Dt.getUVBounds(t.uv),r=Dt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new Ne(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),xi.uvs+=s.uvBuf.numItems}if(t.normals){const e=Dt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new Ne(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),xi.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),xi.indices+=s.indicesBuf.numItems;const o=vt(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),xi.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(),xi.meshes--}}var Bi={};function Fi(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,y=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,b,D,N=0,C=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],u=[],d=[];let f,m,y,g,v,I,_,T,R,P,b,D;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),y=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(y+a),c.push(g+l),c.push(v+h),u.push(1-_/i),u.push(T/r),I=p.normalizeVec3(p.subVec3([y,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,b=(i+1)*(T-1)+_,D=(i+1)*T+_,d.push(R),d.push(P),d.push(b),d.push(b),d.push(D),d.push(R);return E.apply(e,{positions:c,normals:A,uv:u,indices:d})}Bi.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Bi.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Bi.parse._buffToStr(e));window.location.href=s},Bi.clone=function(e){return JSON.parse(JSON.stringify(e))},Bi.bin={},Bi.bin.f=new Float32Array(1),Bi.bin.fb=new Uint8Array(Bi.bin.f.buffer),Bi.bin.rf=function(e,t){for(var s=Bi.bin.f,i=Bi.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},Bi.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Bi.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Bi.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Bi.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Bi.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Bi.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Bi.parse={},Bi.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class Ui extends C{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=p.vec3(t.pos||[0,0,0]),this._up=p.vec3(t.up||[0,1,0]),this._normal=p.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=p.vec3(),this._rtcPos=p.vec3(),this._imageSize=p.vec2(),this._texture=new Si(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 _i(this,{matrix:p.inverseMat4(p.lookAtMat4v(this._pos,p.subVec3(this._pos,this._normal,p.mat4()),this._up,p.mat4())),children:[this._bitmapMesh=new li(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Ot(this,Fi({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Bt(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]}}class Hi extends C{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=p.vec3(),r=V(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),E=Object.entries(y).map((([e,t])=>({color:e,components:t})));o.components.coloring=E;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),o.components.translucency=this._createBCFComponents(t.xrayedObjectIds),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=zi(e.location,Gi),s=zi(e.direction,Gi);h&&p.negateVec3(s),p.subVec3(t,l),r.yUp&&(t=Yi(t),s=Yi(s)),new ui(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),s.push(r++),s.push(r++))})),new Hi(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=zi(e.location,ki),n=zi(e.normal,Vi),a=zi(e.up,ji),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=Yi(o),n=Yi(n),a=Yi(a)),new Ui(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==r.spaces_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const o=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=zi(e.perspective_camera.camera_view_point,Gi),h=zi(e.perspective_camera.camera_direction,Gi),c=zi(e.perspective_camera.camera_up_vector,Gi),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=zi(e.orthogonal_camera.camera_view_point,Gi),h=zi(e.orthogonal_camera.camera_direction,Gi),c=zi(e.orthogonal_camera.camera_up_vector,Gi),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),p.subVec3(a,l),r.yUp&&(a=Yi(a),h=Yi(h),c=Yi(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:p.addVec3(a,h,Gi)}else h=p.addVec3(a,h,Gi);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=p.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function Wi(e){return{x:e[0],y:e[1],z:e[2]}}function zi(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ki(e){return new Float64Array([e[0],-e[2],e[1]])}function Yi(e){return new Float64Array([e[0],e[2],-e[1]])}const Xi=p.vec3(),Zi=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class qi extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new re(s,t.origin),this._targetMarker=new re(s,t.target),this._originWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new oe(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new oe(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new oe(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new oe(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new ae(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new ae(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new ae(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new ae(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,y=s.unitsInfo[m].abbrev;for(var u=0,d=i.length;u{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=t[0]-5+"px",this._markerDiv.style.marginTop=t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),h=e.entity):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class er extends U{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new $i(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.target,i=new qi(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=0)&&(e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),i=!1))}));let o=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{o=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{o=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{o&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class sr{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 s=this._messages[this._locale];if(!s)return null;const i=ir(e,s);return i?t?rr(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=ir(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=rr(r,[t]),s&&(r=rr(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(e,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new t),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=e;const o=this._events[e];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function ir(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?cr._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(p.subVec3(i.eye,i.look,hr),i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,ar),i.look=p.subVec3(ar,hr,nr)):this._flyingLook&&(i.look=p.lerpVec3(s,0,1,this._look1,this._look2,nr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,lr)):this._flyingEyeLookUp&&(i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,ar),i.look=p.lerpVec3(s,0,1,this._look1,this._look2,nr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,lr)),this._projection2){const t="ortho"===this._projection2?cr._easeOutExpo(e,0,1,1):cr._easeInCubic(e,0,1,1);i.customProjection.matrix=p.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();D.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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=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 Ar extends C{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new cr(this),this._t=0,this.state=Ar.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,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case Ar.SCRUBBING:return;case Ar.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=Ar.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Ar.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=Ar.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=Ar.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=Ar.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=Ar.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=Ar.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Ar.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Ar.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Ar.STOPPED=0,Ar.SCRUBBING=1,Ar.PLAYING=2,Ar.PLAYING_TO=3,p.vec3(),p.vec3(),p.vec3(),p.vec3([0,-1,0]),p.vec4([0,0,0,1]);const ur=p.vec3();class pr{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,s){this.numObjects=0,this._mask=s?E.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,h=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;Tr[0]=s,Tr[1]=i,Tr[2]=t.blendCutoff,Tr[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Tr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===vr[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===vr[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===vr[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?_r:Ir)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class Nr extends Dr{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class Cr extends Nr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Or extends Dr{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class Sr extends Or{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class xr extends Dr{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class wr extends Dr{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class Mr extends Dr{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class Br extends Dr{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class Fr extends Nr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class Lr extends Nr{_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,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles 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;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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 = 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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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("outColor = vColor;"),o.push("}"),o}}class Hr extends Cr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Gr extends Cr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class kr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = vPickColor; "),i.push("}"),i}}class Vr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class jr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),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(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Qr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),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;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Wr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class zr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Kr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),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); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Yr extends Nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&(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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),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(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals 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;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" 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(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Zr extends Nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture 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;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),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("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(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("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}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;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e5e6&&(e=5e6),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 eo=p.mat4(),to=p.mat4();function so(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,u=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function oo(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const no=p.vec3(),ao=p.vec3(),lo=p.vec3(),ho=p.vec3(),co=p.mat4();class Ao extends Dr{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=no;let m,y;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=ao;if(l){const e=lo;p.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=G(d,t,co),y=ho,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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()}_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,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${p.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const uo=p.vec3(),po=p.vec3(),fo=p.vec3(),mo=p.vec3(),yo=p.mat4();class Eo extends Dr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=uo;let m,y;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=po;if(l){const e=fo;p.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=G(d,t,yo),y=mo,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_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 s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class go{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Ao(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new Eo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Ao(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Eo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const vo={};const Io=p.mat4(),_o=p.mat4(),To=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.OBB3();const Ro=p.vec3(),Po=p.vec3(),bo=p.vec3(),Do=p.vec3(),No=p.vec3(),Co=p.vec3(),Oo=p.vec3();class So{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._batchingRenderers=function(e){const t=e.id;let s=Jr[t];return s||(s=new qr(e),Jr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=vo[t];return s||(s=new go(e),vo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete vo[t],s._destroy()}))),s}(e.model.scene),this._buffer=new $r(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ye({origin:p.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=p.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=p.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=p.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=p.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=p.collapseAABB3(),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Io;y?p.inverseMat4(p.transposeMat4(y,_o),e):p.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,u=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=ro(d,"floor","ceil"),a=oo(n),h=o(d,a),h>c&&(l=n,c=h),n=ro(d,"ceil","ceil"),a=oo(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,r,r.length,v.normals,v.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):so(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=p.mat4());if(e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new Ne(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=Dt.getUVBounds(s.uv),r=Dt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=p.mat3(r.decodeMatrix),e.uvBuf=new Ne(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Ne(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,i,s.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,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;eE)&&(E=e,i.set(g),r&&p.triangleNormal(d,f,m,r),y=!0)}}return y&&r&&(p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),y}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 xo extends Or{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class wo extends Or{_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,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,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,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// 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 vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Bo extends Sr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Fo extends Sr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Lo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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("outColor = vPickColor; "),i.push("}"),i}}class Uo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Ho extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),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(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Go extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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),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;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class ko extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 Vo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),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,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class jo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const Qo={3e3:"linearToLinear",3001:"sRGBToLinear"};class Wo extends Or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&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("}"),i.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 = "+Qo[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Qo[i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),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(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" 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(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Ko extends Or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),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 mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.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 );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(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;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${p.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sn=p.vec3(),rn=p.vec3(),on=p.vec3(),nn=p.vec3(),an=p.mat4();class ln extends Dr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=sn;let m,y;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=rn;if(l){const e=p.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=G(d,t,an),y=nn,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(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.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_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,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class hn{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new tn(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new ln(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new tn(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new ln(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const cn={};const An=new Uint8Array(4),un=new Float32Array(1),pn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]);const dn=new Float32Array(3),fn=p.vec3(),mn=p.vec3(),yn=p.vec3(),En=p.vec3(),gn=p.vec3(),vn=p.vec3(),In=p.vec3(),_n=new Float32Array(4);class Tn{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Xo[t];return s||(s=new Yo(e),Xo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Xo[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=cn[t];return s||(s=new hn(e),cn[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete cn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ye({numInstances:0,obb:p.OBB3(),origin:p.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=p.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Ne(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new Ne(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new Ne(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=p.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Ne(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Ne(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Ne(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(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,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";An[0]=t[0],An[1]=t[1],An[2]=t[2],An[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(An,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&Q),r=!!(t&X),o=!!(t&Z),n=!!(t&q),a=!!(t&J),l=!!(t&z),h=!!(t&W);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?vr.NOT_RENDERED:s?vr.COLOR_TRANSPARENT:vr.COLOR_OPAQUE,A=!i||h?vr.NOT_RENDERED:n?vr.SILHOUETTE_SELECTED:o?vr.SILHOUETTE_HIGHLIGHTED:r?vr.SILHOUETTE_XRAYED:vr.NOT_RENDERED;let u=0;u=!i||h?vr.NOT_RENDERED:n?vr.EDGES_SELECTED:o?vr.EDGES_HIGHLIGHTED:r?vr.EDGES_XRAYED:a?s?vr.EDGES_COLOR_TRANSPARENT:vr.EDGES_COLOR_OPAQUE:vr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?vr.PICK:vr.NOT_RENDERED)<<12,p|=(t&K?1:0)<<16,un[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(un,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(dn[0]=t[0],dn[1]=t[1],dn[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(dn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=pn,u=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&p.triangleNormal(f,m,y,r),E=!0)}}return E&&r&&(p.transformVec3(a.normalMatrix,r,r),p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),E}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 Rn extends Mr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Pn extends Mr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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;"),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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class bn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Rn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pn(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Dn={};class Nn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.OBB3();class Cn{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Dn[t];return s||(s=new bn(e),Dn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Dn[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new Nn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ye({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=p.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=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=so(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 Sn extends Br{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),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 = 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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class xn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new On(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Sn(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const wn={};const Mn=new Uint8Array(4),Bn=new Float32Array(1);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]);const Fn=new Float32Array(3),Ln=new Float32Array(4);class Un{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=wn[t];return s||(s=new xn(e),wn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete wn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ye({obb:p.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=p.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=p.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Ne(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(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,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Mn[0]=t[0],Mn[1]=t[1],Mn[2]=t[2],Mn[3]=t[3],this._state.colorsBuf.setData(Mn,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&Q),r=!!(t&X),o=!!(t&Z),n=!!(t&q),a=!!(t&J),l=!!(t&z),h=!!(t&W);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?vr.NOT_RENDERED:s?vr.COLOR_TRANSPARENT:vr.COLOR_OPAQUE,A=!i||h?vr.NOT_RENDERED:n?vr.SILHOUETTE_SELECTED:o?vr.SILHOUETTE_HIGHLIGHTED:r?vr.SILHOUETTE_XRAYED:vr.NOT_RENDERED;let u=0;u=!i||h?vr.NOT_RENDERED:n?vr.EDGES_SELECTED:o?vr.EDGES_HIGHLIGHTED:r?vr.EDGES_XRAYED:a?s?vr.EDGES_COLOR_TRANSPARENT:vr.EDGES_COLOR_OPAQUE:vr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?vr.PICK:vr.NOT_RENDERED)<<12,p|=(t&K?255:0)<<16,Bn[0]=p,this._state.flagsBuf.setData(Bn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Fn[0]=t[0],Fn[1]=t[1],Fn[2]=t[2],this._state.offsetsBuf.setData(Fn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;Ln[0]=t[0],Ln[1]=t[4],Ln[2]=t[8],Ln[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ln,s),Ln[0]=t[1],Ln[1]=t[5],Ln[2]=t[9],Ln[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ln,s),Ln[0]=t[2],Ln[1]=t[6],Ln[2]=t[10],Ln[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ln,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}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 Hn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Gn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 kn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class Vn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class jn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Qn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Hn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Gn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new kn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new jn(this._scene)),this._occlusionRenderer}_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()}}const Wn={};class zn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}p.vec4(),p.vec4(),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.OBB3();class Kn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=Wn[t];return s||(s=new Qn(e),Wn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Wn[t],s._destroy()}))),s}(e.model.scene),this._buffer=new zn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ye({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=p.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=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=so(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Xn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class Zn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class qn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Jn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class $n extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 ea extends wr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class ta{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Xn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new $n(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new qn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Jn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ea(this._scene)),this._shadowRenderer}_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()}}const sa={};const ia=new Uint8Array(4),ra=new Float32Array(1);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]);const oa=new Float32Array(3),na=new Float32Array(4);class aa{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=sa[t];return s||(s=new ta(e),sa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete sa[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ye({obb:p.OBB3(),numInstances:0,origin:e.origin?p.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=p.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let i=!1;s.flagsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new Ne(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=p.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new Ne(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new Ne(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;s.pickColorsBuf=new Ne(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(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,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";ia[0]=t[0],ia[1]=t[1],ia[2]=t[2],this._state.colorsBuf.setData(ia,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&Q),r=!!(t&X),o=!!(t&Z),n=!!(t&q),a=!!(t&J),l=!!(t&z),h=!!(t&W);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?vr.NOT_RENDERED:s?vr.COLOR_TRANSPARENT:vr.COLOR_OPAQUE,A=!i||h?vr.NOT_RENDERED:n?vr.SILHOUETTE_SELECTED:o?vr.SILHOUETTE_HIGHLIGHTED:r?vr.SILHOUETTE_XRAYED:vr.NOT_RENDERED;let u=0;u=!i||h?vr.NOT_RENDERED:n?vr.EDGES_SELECTED:o?vr.EDGES_HIGHLIGHTED:r?vr.EDGES_XRAYED:a?s?vr.EDGES_COLOR_TRANSPARENT:vr.EDGES_COLOR_OPAQUE:vr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?vr.PICK:vr.NOT_RENDERED)<<12,p|=(t&K?255:0)<<16,ra[0]=p,this._state.flagsBuf.setData(ra,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(oa[0]=t[0],oa[1]=t[1],oa[2]=t[2],this._state.offsetsBuf.setData(oa,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;na[0]=t[0],na[1]=t[4],na[2]=t[8],na[3]=t[12],this._state.modelMatrixCol0Buf.setData(na,s),na[0]=t[1],na[1]=t[5],na[2]=t[9],na[3]=t[13],this._state.modelMatrixCol1Buf.setData(na,s),na[0]=t[2],na[1]=t[6],na[2]=t[10],na[3]=t[14],this._state.modelMatrixCol2Buf.setData(na,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.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._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,vr.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,vr.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,vr.PICK)}drawPickNormals(e,t){}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()}}class la{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class ha{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const ca={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={}}};const Aa=new class{constructor(e,t,s){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=s}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,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==ua[e])return void ua[e].push({onLoad:t,onProgress:s,onError:i});ua[e]=[],ua[e].push({onLoad:t,onProgress:s,onError:i});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 s=ua[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.length;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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{ca.add(e,t);const s=ua[e];delete ua[e];for(let e=0,i=s.length;e{const s=ua[e];if(void 0===s)throw this.manager.itemError(e),t;delete ua[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class da{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{const i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let fa=0;class ma{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new da,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new pa;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new pa;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=ma.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(ma.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(ma.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(ma.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),fa>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),fa++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?ts:is,magFilter:1===o.length?ts:is,encoding:2===A?ys:ms,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),fa--}}ma.BasisFormat={ETC1S:0,UASTC_4x4:1},ma.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},ma.EngineFormat={RGBAFormat:os,RGBA_ASTC_4x4_Format:ds,RGBA_BPTC_Format:fs,RGBA_ETC2_EAC_Format:ps,RGBA_PVRTC_4BPPV1_Format:As,RGBA_S3TC_DXT5_Format:hs,RGB_ETC1_Format:36196,RGB_ETC2_Format:us,RGB_PVRTC_4BPPV1_Format:cs,RGB_S3TC_DXT1_Format:ns},ma.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),y=n.getDFDFlags(),{transcoderFormat:E,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const s=this._getNextId(),n=new i(s);for(let s=0,i=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new o(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(r);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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("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;ewindow.innerHeight&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}let a=!0,l=a?Float64Array:Float32Array;const h=new l(3),c=new l(16),A=new l(16),u=new l(4),p={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 s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+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){},doublesToFloats(e,t,s){const i=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new l(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>p.dotVec4(e,e),lenVec4:e=>Math.sqrt(p.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=>p.dotVec3(e,e),sqLenVec2:e=>p.dotVec2(e,e),lenVec3:e=>Math.sqrt(p.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,s)=>p.lenVec3(p.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(p.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,s)=>p.lenVec2(p.subVec2(t,s,e))})(),rcpVec3:(e,t)=>p.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/p.lenVec4(e);return p.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/p.lenVec3(e);return p.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/p.lenVec2(e);return p.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=p.dotVec3(e,t)/Math.sqrt(p.sqLenVec3(e)*p.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=p.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=p.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=p.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||p.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:()=>p.m4s(0),setMat4ToOnes:()=>p.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,s,i)=>p.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>p.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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>p.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],y=e[14],E=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],b=t[7],D=t[8],N=t[9],C=t[10],O=t[11],S=t[12],x=t[13],w=t[14],M=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*y,s[3]=g*n+v*c+I*d+_*E,s[4]=T*i+R*a+P*A+b*f,s[5]=T*r+R*l+P*u+b*m,s[6]=T*o+R*h+P*p+b*y,s[7]=T*n+R*c+P*d+b*E,s[8]=D*i+N*a+C*A+O*f,s[9]=D*r+N*l+C*u+O*m,s[10]=D*o+N*h+C*p+O*y,s[11]=D*n+N*c+C*d+O*E,s[12]=S*i+x*a+w*A+M*f,s[13]=S*r+x*l+w*u+M*m,s[14]=S*o+x*h+w*p+M*y,s[15]=S*n+x*c+w*d+M*E,s},mulMat3(e,t,s){s||(s=new l(9));const i=e[0],r=e[3],o=e[6],n=e[1],a=e[4],h=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],y=t[4],E=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*y+o*v,s[6]=i*f+r*E+o*I,s[1]=n*p+a*m+h*g,s[4]=n*d+a*y+h*v,s[7]=n*f+a*E+h*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*y+u*v,s[8]=c*f+A*E+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=p.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],y=e[15],E=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,b=c*y-p*d,D=A*m-u*f,N=A*y-p*f,C=u*y-p*m,O=1/(E*C-g*N+v*D+I*b-_*P+T*R);return t[0]=(a*C-l*N+h*D)*O,t[1]=(-i*C+r*N-o*D)*O,t[2]=(f*T-m*_+y*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*C+l*b-h*P)*O,t[5]=(s*C-r*b+o*P)*O,t[6]=(-d*T+m*v-y*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*N-a*b+h*R)*O,t[9]=(-s*N+i*b-o*R)*O,t[10]=(d*_-f*v+y*E)*O,t[11]=(-c*_+A*v-p*E)*O,t[12]=(-n*D+a*P-l*R)*O,t[13]=(s*D-i*P+r*R)*O,t[14]=(-d*I+f*g-m*E)*O,t[15]=(c*I-A*g+u*E)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||p.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||p.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.translationMat4v(e,r))})(),translationMat4s:(e,t)=>p.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>p.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=p.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,u,d,f,m;return c=a*l,A=l*h,u=h*a,d=a*r,f=l*r,m=h*r,(s=s||p.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*u-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*u+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>p.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=p.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=p.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>p.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=p.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,u=i*h,d=r*l,f=r*h,m=o*h,y=n*a,E=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=u-E,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+y,s[7]=0,s[8]=u+E,s[9]=f-y,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=p.vec4()){const i=p.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],u=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,u),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,u),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,u),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,u),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,u))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,u),s[1]=0)),s},composeMat4:(e,t,s,i=p.mat4())=>(p.quaternionToRotationMat4(t,i),p.scaleMat4v(s,i),p.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=p.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=p.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=p.lenVec3(e);p.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,p.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=p.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],u=t[2];if(r===c&&o===A&&n===u)return p.identityMat4();let d,f,m,y,E,g,v,I,_,T;return d=r-c,f=o-A,m=n-u,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,y=l*m-h*f,E=h*d-a*m,g=a*f-l*d,T=Math.sqrt(y*y+E*E+g*g),T?(T=1/T,y*=T,E*=T,g*=T):(y=0,E=0,g=0),v=f*g-m*E,I=m*y-d*g,_=d*E-f*y,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=y,i[1]=v,i[2]=d,i[3]=0,i[4]=E,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(y*r+E*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>p.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=p.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];p.addVec4(r,i,c),p.subVec4(r,i,A);const o=2*i[2],n=A[0],a=A[1],l=A[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=c[0]/n,s[9]=c[1]/a,s[10]=-c[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],p.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,s=p.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=p.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],y=e[8],E=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),s=new l(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||p.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||p.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=p.vec4()){const i=e[0]*p.DEGTORAD/2,r=e[1]*p.DEGTORAD/2,o=e[2]*p.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=p.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const u=s+n+c;return u>0?(A=.5/Math.sqrt(u+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=p.vec4()){const i=Math.sqrt(p.dotVec3(e,e)*p.dotVec3(t,t));let r=i+p.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):p.cross3Vec3(e,t,s),s[3]=r,p.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=p.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new l(16);return(t,s,i)=>(i=i||p.vec3(),p.quaternionToRotationMat4(t,e),p.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=p.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=p.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,u=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-u*-a,s[1]=A*h+d*-a+u*-n-c*-l,s[2]=u*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=p.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,u=n*s,d=a*s,f=l*s,m=a*i,y=l*i,E=l*r;return t[0]=1-(m+E),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(u+E),t[6]=y+h,t[8]=f+c,t[9]=y-h,t[10]=1-(u+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,y=o*l;return t[0]=1-(u+d),t[4]=c-y,t[8]=A+m,t[1]=c+y,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+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 s=p.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,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)=>p.normalizeQuaternion(p.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=p.vec4()){const s=(e=p.normalizeQuaternion(e,u))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,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,s,i)=>new l([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],y=e[9],E=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new l(3),t=new l(3),s=new l(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],p.subVec3(t,e,s),Math.abs(p.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=p.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(p.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||p.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||p.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=p.AABB3())=>(e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MAX_DOUBLE,e[3]=p.MIN_DOUBLE,e[4]=p.MIN_DOUBLE,e[5]=p.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=p.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,s,i)=>{s=s||p.AABB3();let r,o,n,a=p.MAX_DOUBLE,l=p.MAX_DOUBLE,h=p.MAX_DOUBLE,c=p.MIN_DOUBLE,A=p.MIN_DOUBLE,u=p.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>u&&(u=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=u,s}})(),OBB3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new l(3);return(t,s)=>{s=s||p.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=p.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=p.vec3()){let s=0,i=0,r=0;for(var o=0,n=e.length;o(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](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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MIN_DOUBLE,e[3]=p.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=p.AABB2()){let s,i,r,o,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=p.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,u=r*l-o*a,d=Math.sqrt(c*c+A*A+u*u);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=u/d),i},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3);return(o,n,a,l,h,c)=>{c=c||p.vec3();const A=p.subVec3(l,a,e),u=p.subVec3(h,a,t),d=p.cross3Vec3(n,u,s),f=p.dotVec3(A,d);if(f<1e-6)return null;const m=p.subVec3(o,a,i),y=p.dotVec3(m,d);if(y<0||y>f)return null;const E=p.cross3Vec3(m,A,r),g=p.dotVec3(n,E);if(g<0||y+g>f)return null;const v=p.dotVec3(u,E)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3);return(r,o,n,a,l,h)=>{h=h||p.vec3(),o=p.normalizeVec3(o,e);const c=p.subVec3(a,n,t),A=p.subVec3(l,n,s),u=p.cross3Vec3(c,A,i);p.normalizeVec3(u,u);const d=-p.dotVec3(n,u),f=-(p.dotVec3(r,u)+d)/p.dotVec3(o,u);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r,o,n,a)=>{const l=p.subVec3(n,r,e),h=p.subVec3(o,r,t),c=p.subVec3(i,r,s),A=p.dotVec3(l,l),u=p.dotVec3(l,h),d=p.dotVec3(l,c),f=p.dotVec3(h,h),m=p.dotVec3(h,c),y=A*f-u*u;if(0===y)return null;const E=1/y,g=(f*d-u*m)*E,v=(A*m-u*d)*E;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=p.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,y=0;for(f=0,m=e.length;f{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let u,d,f,m,y,E,g;for(h=0,c=a.length;h{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const u=1e4;let d,f,m,y,E,g;for(f=0,y=e.length;f{const e=new l(4),t=new l(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,p.transformVec4(s,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],p.transformVec3(s,e,t),p.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),s=new l(4),i=new l(4),r=new l(4),o=new l(4);return(n,a,l,h,c,A)=>{const u=p.mulMat4(l,a,e),d=p.inverseMat4(u,t),f=n.width,m=n.height,y=(h[0]-f/2)/(f/2),E=-(h[1]-m/2)/(m/2);s[0]=y,s[1]=E,s[2]=-1,s[3]=1,p.transformVec4(d,s,i),p.mulVec4Scalar(i,1/i[3]),r[0]=y,r[1]=E,r[2]=1,r[3]=1,p.transformVec4(d,r,o),p.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],p.subVec3(o,i,A),p.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(s,i,r,o,n,a,l)=>{p.canvasPosToWorldRay(s,i,r,n,e,t),p.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),s=new l(4);return(i,r,o,n,a)=>{const l=p.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,p.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],p.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let h,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,h=0,c=s.length;hn[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(s.length<20||o>10)return a.triangles=s,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 p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let y=0;for(h=0,c=s.length;h{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};p.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}(),p.planeClipsPositions3=function(e,t,s,i=3){for(let r=0,o=s.length;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;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),s=new Uint8Array(e);for(var n=0;n=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}},_={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let R,P=0,b=0;const D=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(D.scenes[e.id])return void console.error(`[ERROR] Scene ${E.inQuotes(e.id)} already exists`)}else e.id=v.addItem({});D.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;g[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{v.removeItem(e.id),delete D.scenes[e.id],delete g[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in D.scenes)D.scenes.hasOwnProperty(t)&&(e=D.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete D.scenes[e.id]))},this.scheduleTask=function(e,t){I.push(e),I.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;I.length>0&&(e<0||i0&&R>0){var t=1e3/R;b+=t,T.push(t),T.length>=30&&(b-=T.shift()),d.frame.fps=Math.round(b/T.length)}!function(e){const t=D.runTasks(e+10),s=D.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in _.time=e,D.scenes)if(D.scenes.hasOwnProperty(t)){var s=D.scenes[t];_.sceneId=t,_.startTime=s.startTime,_.deltaTime=null!=_.prevTime?_.time-_.prevTime:0,s.fire("tick",_,!0)}_.prevTime=e}(e),function(){const e=D.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=g[n],i||(i=g[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),P=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(N):requestAnimationFrame(N)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(N):requestAnimationFrame(N);class C{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 C))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,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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+" "+E.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 s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(E.isNumeric(s)||E.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+E.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+E.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+E.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():D.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_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,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class M{constructor(){this.planes=[new w,new w,new w,new w,new w,new w]}}function B(e,t,s){const i=p.mulMat4(s,t,x),r=i[0],o=i[1],n=i[2],a=i[3],l=i[4],h=i[5],c=i[6],A=i[7],u=i[8],d=i[9],f=i[10],m=i[11],y=i[12],E=i[13],g=i[14],v=i[15];e.planes[0].set(a-r,A-l,m-u,v-y),e.planes[1].set(a+r,A+l,m+u,v+y),e.planes[2].set(a-o,A-h,m-d,v-E),e.planes[3].set(a+o,A+h,m+d,v+E),e.planes[4].set(a-n,A-c,m-f,v-g),e.planes[5].set(a+n,A+c,m+f,v+g)}function F(e,t){let s=M.INSIDE;const i=O,r=S;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return M.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=M.INTERSECT)}return s}M.INSIDE=0,M.INTERSECT=1,M.OUTSIDE=2;class L extends C{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=p.vec2(),this._canvasMarqueeCorner2=p.vec2(),this._canvasMarquee=p.AABB2(),this._marqueeFrustum=new M,this._marqueeFrustumProjMat=p.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!==L.PICK_MODE_INSIDE&&e!==L.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===L.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=(s,i=M.INTERSECT)=>{if(i===M.INTERSECT&&(i=F(this._marqueeFrustum,s.aabb)),i!==M.OUTSIDE){if(s.entities){const t=s.entities;for(let s=0,i=t.length;s3||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,s=e.clientHeight,i=e.clientLeft,r=e.clientTop,o=2/t,n=2/s,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-i)*o-1,h=(this._canvasMarquee[2]-i)*o-1,c=-(this._canvasMarquee[3]-r)*n+1,A=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);p.frustumMat4(l,h,c*a,A*a,u,1e4,this._marqueeFrustumProjMat),B(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)}}L.PICK_MODE_INTERSECTS=0,L.PICK_MODE_INSIDE=1;class U{constructor(e,t,s){this.id=s&&s.id?s.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)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}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)}}const H=p.vec3(),G=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(i,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,p.transformVec4(i,t,s),p.setMat4Translation(i,s,o),o.slice()}}();function k(e,t,s){const i=Float32Array.from([e[0]])[0],r=e[0]-i,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=i,t[1]=o,t[2]=a,s[0]=r,s[1]=n,s[2]=l}function V(e,t,s,i=1e3){const r=p.getPositionsCenter(e,H),o=Math.round(r[0]/i)*i,n=Math.round(r[1]/i)*i,a=Math.round(r[2]/i)*i;s[0]=o,s[1]=n,s[2]=a;const l=0!==s[0]||0!==s[1]||0!==s[2];if(l)for(let s=0,i=e.length;s0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(p.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){se.set(this._viewPos),se[3]=1,p.transformPoint4(this.scene.camera.projMatrix,se,ie);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ie[0]/ie[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ie[1]/ie[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){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof te?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)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),k(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._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class oe{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class ne{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!0,this._culled=!1;var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&r.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ae{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var le=p.vec3(),he=p.vec3();class ce extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new re(s,t.origin),this._cornerMarker=new re(s,t.corner),this._targetMarker=new re(s,t.target),this._originWorld=p.vec3(),this._cornerWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new oe(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new oe(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new ae(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>u||f>u||m>u)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const y=this._container.getBoundingClientRect();for(var r=i.top-y.top,o=i.left-y.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.canvasPos=e.canvasPos,i.snappedCanvasPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const s=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),h.set(s),this._mouseState){case 0:this.markerDiv.style.marginLeft=s[0]-5+"px",this.markerDiv.style.marginTop=s[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,i&&(i.visible=!0,i.pointerPos=e.canvasPos,i.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class pe extends U{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new ue(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.corner,i=e.target,r=new ce(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t
',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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.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 s=this._element;s&&(s.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 fe=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class me extends C{constructor(e,t={}){super(e,t),this._backgroundColor=p.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 s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new de(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-"+p.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Ee.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Ee.FS_MAX_FLOAT_PRECISION="mediump":Ee.FS_MAX_FLOAT_PRECISION="lowp":Ee.FS_MAX_FLOAT_PRECISION="mediump",Ee.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Ee.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Ee.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Ee.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Ee.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ee.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Ee.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Ee.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Ee.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Ee.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Ee.SUPPORTED_EXTENSIONS[e]=!0})))}class ve{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}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}}class Ie{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function be(e){console.error(e.join("\n"))}class De{constructor(e,t){this.id=Re.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 Ie(e,e.VERTEX_SHADER,Pe(this.source.vertex)),this._fragmentShader=new Ie(e,e.FRAGMENT_SHADER,Pe(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void be(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void be(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void be(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void be(this.errors);let t,s,i,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 be(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ce{constructor(e,t){this.scene=e,this.aabb=p.AABB3(),this.origin=p.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-t){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{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 s=this._occlusionLayers[t];s||(s=new Ce(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ce(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.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;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new De(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),u=Math.random(),d="perspective"===i.camera.projection;we[0]=o,we[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,we),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();s.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)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new De(s,{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 i=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 Ne(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new Ne(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new Ne(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.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 Be=new Float32Array(ke(17,[0,1])),Fe=new Float32Array(ke(17,[1,0])),Le=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(Ge(i,t));return s}(17,4)),Ue=new Float32Array(2);class He{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 De(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]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Ne(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new Ne(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Ne(e,e.ELEMENT_ARRAY_BUFFER,i,i.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,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Ue[0]=n,Ue[1]=a,i.uniform2fv(this._uViewport,Ue),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Fe):i.uniform2fv(this._uSampleOffsets,Be),i.uniform1fv(this._uSampleWeights,Le);const A=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Ge(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ke(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class Ve{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.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,s=null){const i=this.gl,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),s?i.texStorage2D(i.TEXTURE_2D,1,s,e,t):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),r}_touch(...e){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;this.buffer.textures.forEach((e=>i.deleteTexture(e))),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,s,e)))):r.push(this.createTexture(t,s)),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();i.bindFramebuffer(i.FRAMEBUFFER,a);for(let e=0;e0&&i.drawBuffers(r.map(((e,t)=>i.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.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:s},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,s=null,i=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,h=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,s||c.RGBA,i||c.UNSIGNED_BYTE,h,0),h}readArray(e=null,t=null,s=Uint8Array,i=4,r=0){const o=new s(this.buffer.width*this.buffer.height*i),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(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;ee.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 je{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let i=s[e];return i||(i=new Ve(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=i),i}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Qe(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=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":s=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":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}const We=function(e,s){s=s||{};const i=new ye(e),r=e.canvas.canvas,o=e.canvas.gl,n=!!s.transparent,a=s.alphaDepthMask,l=new t({});let h={},c={},A=!0,u=!0,f=!0,m=!0,y=!0,E=!0,g=!0,v=!0;const I=new je(e);let _=!1;const T=new Me(e),R=new He(e);function P(){A&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableMap,i=t.drawableListPreCull;let r=0;for(let e in s)s.hasOwnProperty(e)&&(i[r++]=s[e]);i.length=r}}(),A=!1,u=!0),u&&(!function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),u=!1,f=!0),f&&function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],s=t.drawableListPreCull,i=t.drawableList;let r=0;for(let e=0,t=s.length;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.lastProgramId=null,e.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.lastProgramId=null,e.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=u.size[0],i=t%s-Math.floor(s/2),r=Math.floor(t/s)-Math.floor(s/2),o=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));D.push({x:i,y:r,dist:o,isVertex:n&&a?E[e+3]>y.length/2:n,result:[E[e+0],E[e+1],E[e+2],E[e+3]],normal:[g[e+0],g[e+1],g[e+2],g[e+3]],id:[v[e+0],v[e+1],v[e+2],v[e+3]]})}let S=null,x=null,w=null,M=null;if(D.length>0){D.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),M=D[0].isVertex?"vertex":"edge";const e=D[0].result,t=D[0].normal,s=D[0].id,i=y[e[3]],r=i.origin,o=i.coordinateScale;x=p.normalizeVec3([t[0]/p.MAX_INT,t[1]/p.MAX_INT,t[2]/p.MAX_INT]),S=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],w=l.items[s[0]+(s[1]<<8)+(s[2]<<16)+(s[3]<<24)]}if(null===_&&null==S)return null;let B=null;null!==S&&(B=e.camera.projectWorldPos(S));const F=w&&w.delegatePickedEntity?w.delegatePickedEntity():w;return c.reset(),c.snappedToEdge="edge"===M,c.snappedToVertex="vertex"===M,c.worldPos=S,c.worldNormal=x,c.entity=F,c.canvasPos=s,c.snappedCanvasPos=B||s,c}}(),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new xe(e,I),this._occlusionTester.addMarker(t),e.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){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.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 in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=t.length;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())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,s)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));t(i)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!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("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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()}}const Ke=new t({});class Ye{constructor(e){this.id=Ke.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){Ke.removeItem(this.id)}}class Xe extends C{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Ye({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],s=e[3];this._state.boundary=[0,0,t,s],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 Ze extends C{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),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],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),p.perspectiveMat4(i*(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:2e3;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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class qe extends C{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),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,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),p.orthoMat4c(n,a,h,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:2e3;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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class Je extends C{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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(){p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class $e extends C{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ye({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const et=p.vec3(),tt=p.vec3(),st=p.vec3(),it=p.vec3(),rt=p.vec3(),ot=p.vec3(),nt=p.vec4(),at=p.vec4(),lt=p.vec4(),ht=p.mat4(),ct=p.mat4(),At=p.vec3(),ut=p.vec3(),pt=p.vec3(),dt=p.vec3();class ft extends C{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Ye({deviceMatrix:p.mat4(),hasDeviceMatrix:!1,matrix:p.mat4(),normalMatrix:p.mat4(),inverseMatrix:p.mat4()}),this._perspective=new Ze(this),this._ortho=new qe(this),this._frustum=new Je(this),this._customProjection=new $e(this),this._project=this._perspective,this._eye=p.vec3([0,0,10]),this._look=p.vec3([0,0,0]),this._up=p.vec3([0,1,0]),this._worldUp=p.vec3([0,1,0]),this._worldRight=p.vec3([1,0,0]),this._worldForward=p.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?(p.subVec3(this._eye,this._look,At),p.normalizeVec3(At,ut),p.mulVec3Scalar(ut,1e3,pt),p.addVec3(this._look,pt,dt),t=dt):t=this._eye,e.hasDeviceMatrix?(p.lookAtMat4v(t,this._look,this._up,ct),p.mulMat4(e.deviceMatrix,ct,e.matrix)):p.lookAtMat4v(t,this._look,this._up,e.matrix),p.inverseMat4(this._state.matrix,this._state.inverseMatrix),p.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=p.subVec3(this._eye,this._look,et);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ht),t=p.transformPoint3(ht,t,tt),this.eye=p.addVec3(this._look,t,st),this.up=p.transformPoint3(ht,this._up,it)}orbitPitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._eye,this._look,et);const s=p.cross3Vec3(p.normalizeVec3(t,tt),p.normalizeVec3(this._up,st));p.rotationMat4v(.0174532925*e,s,ht),t=p.transformPoint3(ht,t,it),this.up=p.transformPoint3(ht,this._up,rt),this.eye=p.addVec3(t,this._look,ot)}yaw(e){let t=p.subVec3(this._look,this._eye,et);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ht),t=p.transformPoint3(ht,t,tt),this.look=p.addVec3(t,this._eye,st),this._gimbalLock&&(this.up=p.transformPoint3(ht,this._up,it))}pitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._look,this._eye,et);const s=p.cross3Vec3(p.normalizeVec3(t,tt),p.normalizeVec3(this._up,st));p.rotationMat4v(.0174532925*e,s,ht),this.up=p.transformPoint3(ht,this._up,ot),t=p.transformPoint3(ht,t,it),this.look=p.addVec3(t,this._eye,rt)}pan(e){const t=p.subVec3(this._eye,this._look,et),s=[0,0,0];let i;if(0!==e[0]){const r=p.cross3Vec3(p.normalizeVec3(t,[]),p.normalizeVec3(this._up,tt));i=p.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=p.mulVec3Scalar(p.normalizeVec3(this._up,st),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=p.mulVec3Scalar(p.normalizeVec3(t,it),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=p.addVec3(this._eye,s,rt),this.look=p.addVec3(this._look,s,ot)}zoom(e){const t=p.subVec3(this._eye,this._look,et),s=Math.abs(p.lenVec3(t,tt)),i=Math.abs(s+e);if(i<.5)return;const r=p.normalizeVec3(t,st);this.eye=p.addVec3(this._look,p.mulVec3Scalar(r,i),it)}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=p.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 p.lenVec3(p.subVec3(this._look,this._eye,et))}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}projectWorldPos(e){const t=nt,s=at,i=lt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,p.mulMat4v4(this.viewMatrix,t,s),p.mulMat4v4(this.projMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class mt extends C{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class yt extends mt{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 s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Ye({type:"dir",dir:p.vec3([1,1,1]),color:p.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=p.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];p.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=p.identityMat4()),p.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Ve(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 Et extends mt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:p.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 gt extends C{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),d.memory.meshes++}destroy(){super.destroy(),d.memory.meshes--}}var vt=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(y,E,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[C.index1],M=s[C.index2],(!B&&w>65535||M>65535)&&(B=!0),I.push(w),I.push(M));return B?new Uint32Array(I):new Uint16Array(I)}}();const It=function(){const e=p.mat4(),t=p.mat4();return function(s,i){i=i||p.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return p.identityMat4(e),p.translationMat4v(s,e),p.identityMat4(t),p.scalingMat4v([a/c,l/c,h/c],t),p.mulMat4(e,t,i),i}}();var _t=function(){const e=p.mat4(),t=p.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function Pt(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function bt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const Dt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=Rt(e,a,"floor","ceil"),i=Pt(s),o=bt(e,a,i),o>n&&(r=s,n=o),s=Rt(e,a,"ceil","ceil"),i=Pt(s),o=bt(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},Nt=d.memory,Ct=p.AABB3();class Ot extends gt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ye({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 s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Dt.getPositionsBounds(t.positions),i=Dt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Dt.getUVBounds(t.uv),i=Dt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=Dt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.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(),Nt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Nt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Nt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new Ne(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),Nt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Nt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Ne(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Nt.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,s=vt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),Nt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=p.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new Ne(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Nt.positions+=this._pickTrianglePositionsBuf.numItems,Nt.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),Dt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=Dt.getPositionsBounds(e),i=Dt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),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),Dt.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,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),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),Dt.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,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),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,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),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=p.AABB3()),p.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=p.OBB3()),p.positions3ToAABB3(this._state.positions,Ct,this._state.positionsDecodeMatrix),p.AABB3ToOBB3(Ct,this._obb),this._obbDirty=!1),this._obb}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(),Nt.meshes--}}function St(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return E.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,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]})}class xt extends C{get type(){return"Material"}constructor(e,t={}){super(e,t),d.memory.materials++}destroy(){super.destroy(),d.memory.materials--}}const wt={opaque:0,mask:1,blend:2},Mt=["opaque","mask","blend"];class Bt extends xt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Ye({type:"PhongMaterial",ambient:p.vec3([1,1,1]),diffuse:p.vec3([1,1,1]),specular:p.vec3([1,1,1]),emissive:p.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=wt[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 Mt[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()}}const Ft={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 Lt extends xt{get type(){return"EmphasisMaterial"}get presets(){return Ft}constructor(e,t={}){super(e,t),this._state=new Ye({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(e=e||"default",this._preset===e)return;const t=Ft[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(Ft).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Ut={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 Ht extends xt{get type(){return"EdgeMaterial"}get presets(){return Ut}constructor(e,t={}){super(e,t),this._state=new Ye({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=Ut[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(Ut).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Gt={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 kt extends C{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=p.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return Gt}set units(e){e||(e="meters");Gt[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=p.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=p.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 Vt extends C{constructor(e,t={}){super(e,t),this._supported=Ee.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()}}const jt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Qt extends xt{get type(){return"PointsMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new Ye({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=jt[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(jt).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 Wt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class zt extends xt{get type(){return"LinesMaterial"}get presets(){return Wt}constructor(e,t={}){super(e,t),this._state=new Ye({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=Wt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Wt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Kt(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new We(this,{transparent:i,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 s=[];for(let e=0,i=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=p.vec4([0,0,0,0]),t=p.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,i=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let i;for(let s=0,r=t.length;s0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+E.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=p.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[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,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],E.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_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)}_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)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_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)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(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}_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}_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 s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}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}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&D.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 s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=Kt(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=Kt(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}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,s=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=p.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){E.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i{r>i&&(i=r,e(...s))}));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.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.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const Xt=1e3,Zt=1001,qt=1002,Jt=1003,$t=1004,es=1005,ts=1006,ss=1007,is=1008,rs=1008,os=1023,ns=33776,as=33777,ls=33778,hs=33779,cs=35840,As=35842,us=37492,ps=37496,ds=37808,fs=36492,ms=3e3,ys=3001,Es=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,i=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=s.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.lights.length;e0,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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.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),A=Is(e),u=i.getNumAllocatedSectionPlanes()>0,p=vs(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&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;"),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(A){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= 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;"),d&&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] = 1.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] = 1.0;"),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(p){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;e0&&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;e0,l=Is(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=vs(e);t.gammaInput;const d=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;"));p&&(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("}"),d&&(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;m0&&(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 = "+gs[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("}")),(A||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 = "+gs[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._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("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._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("}"),s._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;")),s._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;")),s._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;")),s._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;")),s._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 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._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 = "+gs[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+gs[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+gs[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+gs[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._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)){h&&s._normalMap?(s._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);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._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;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._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);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._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;")),A&&(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||A)&&(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;e0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class bs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 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] = 1.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] = 1.0;"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.lights.length;e0,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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ds=new t({}),Ns=p.vec3(),Cs=function(e,t){this.id=Ds.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new bs(t),this._allocate(t)},Os={};Cs.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 s=Os[t];return s||(s=new Cs(t,e),Os[t]=s,d.memory.programs++),s._useCount++,s},Cs.prototype.put=function(){0==--this._useCount&&(Ds.removeItem(this.id),this._program&&this._program.destroy(),delete Os[this._hash],d.memory.programs--)},Cs.prototype.webglContextRestored=function(){this._program=null},Cs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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] = 1.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] = 1.0;"),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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.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;"));i&&(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=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const xs=new t({}),ws=p.vec3(),Ms=function(e,t){this.id=xs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ss(t),this._allocate(t)},Bs={};Ms.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 s=Bs[t];return s||(s=new Ms(t,e),Bs[t]=s,d.memory.programs++),s._useCount++,s},Ms.prototype.put=function(){0==--this._useCount&&(xs.removeItem(this.id),this._program&&this._program.destroy(),delete Bs[this._hash],d.memory.programs--)},Ms.prototype.webglContextRestored=function(){this._program=null},Ms.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=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=i._sectionPlanesState.getNumAllocatedSectionPlanes(),s=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.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;"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 Ls=p.vec3(),Us=function(e,t){this._hash=e,this._shaderSource=new Fs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Hs={};Us.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Hs[t];if(!s){if(s=new Us(t,e),s.errors)return console.log(s.errors.join("\n")),null;Hs[t]=s,d.memory.programs++}return s._useCount++,s},Us.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Hs[this._hash],d.memory.programs--)},Us.prototype.webglContextRestored=function(){this._program=null},Us.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},Us.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new De(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 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 ks=p.vec3(),Vs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Gs(t),this._allocate(t)},js={};Vs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=js[t];if(!s){if(s=new Vs(t,e),s.errors)return console.log(s.errors.join("\n")),null;js[t]=s,d.memory.programs++}return s._useCount++,s},Vs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete js[this._hash],d.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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] = 1.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] = 1.0;"),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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.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(i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 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 Ws=p.vec3(),zs=function(e,t){this._hash=e,this._shaderSource=new Qs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ks={};zs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Ks[t];if(!s){if(s=new zs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ks[t]=s,d.memory.programs++}return s._useCount++,s},zs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ks[this._hash],d.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),r=s._sectionPlanesState.sectionPlanes.length;if(e>0){const o=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.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"),i){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Xs=function(e,t){this._hash=e,this._shaderSource=new Ys(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Zs={};Xs.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Zs[s];if(!i){if(i=new Xs(s,e),i.errors)return console.log(i.errors.join("\n")),null;Zs[s]=i,d.memory.programs++}return i._useCount++,i},Xs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Zs[this._hash],d.memory.programs--)},Xs.prototype.webglContextRestored=function(){this._program=null},Xs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Xs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new De(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const hi=function(){const e=p.vec3(),t=p.vec3(),s=p.vec3(),i=p.vec3(),r=p.vec3(),o=p.vec3(),n=p.vec4(),a=p.vec3(),l=p.vec3(),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3(),y=p.vec4(),E=p.vec4(),g=p.vec4(),v=p.vec3(),I=p.vec3(),_=p.vec3(),T=p.vec3(),R=p.vec3(),P=p.vec3(),b=p.vec3(),D=p.vec3(),N=p.vec3(),C=p.vec3(),O=p.vec3();return function(S,x,w,M){var B=M.primIndex;if(null!=B&&B>-1){const H=S.geometry._state,k=S.scene,V=k.camera,j=k.canvas;if("triangles"===H.primitiveName){M.primitive="triangle";const k=B,Q=H.indices,W=H.positions;let z,K,Y;if(Q){var F=Q[k+0],L=Q[k+1],U=Q[k+2];o[0]=F,o[1]=L,o[2]=U,M.indices=o,z=3*F,K=3*L,Y=3*U}else z=3*k,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],H.compressGeometry){const e=H.positionsDecodeMatrix;e&&(Dt.decompressPosition(s,e,s),Dt.decompressPosition(i,e,i),Dt.decompressPosition(r,e,r))}M.canvasPos?p.canvasPosToLocalRay(j.canvas,S.origin?G(x,S.origin):x,w,S.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&p.worldRayToLocalRay(S.worldMatrix,M.origin,M.direction,e,t),p.normalizeVec3(t),p.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,y[0]=n[0],y[1]=n[1],y[2]=n[2],y[3]=1,p.transformVec4(S.worldMatrix,y,E),a[0]=E[0],a[1]=E[1],a[2]=E[2],M.canvasPos&&S.origin&&(a[0]+=S.origin[0],a[1]+=S.origin[1],a[2]+=S.origin[2]),M.worldPos=a,p.transformVec4(V.matrix,E,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,p.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=H.normals;if(X){if(H.compressGeometry){const e=3*F,t=3*L,s=3*U;Dt.decompressNormal(X.subarray(e,e+2),c),Dt.decompressNormal(X.subarray(t,t+2),A),Dt.decompressNormal(X.subarray(s,s+2),u)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],u[0]=X[Y],u[1]=X[Y+1],u[2]=X[Y+2];const e=p.addVec3(p.addVec3(p.mulVec3Scalar(c,h[0],v),p.mulVec3Scalar(A,h[1],I),_),p.mulVec3Scalar(u,h[2],T),R);M.worldNormal=p.normalizeVec3(p.transformVec3(S.worldNormalMatrix,e,P))}const Z=H.uv;if(Z){if(d[0]=Z[2*F],d[1]=Z[2*F+1],f[0]=Z[2*L],f[1]=Z[2*L+1],m[0]=Z[2*U],m[1]=Z[2*U+1],H.compressGeometry){const e=H.uvDecodeMatrix;e&&(Dt.decompressUV(d,e,d),Dt.decompressUV(f,e,f),Dt.decompressUV(m,e,m))}M.uv=p.addVec3(p.addVec3(p.mulVec2Scalar(d,h[0],b),p.mulVec2Scalar(f,h[1],D),N),p.mulVec2Scalar(m,h[2],C),O)}}}}}();function ci(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],y=[],g=[],v=[];let I,_,T,R,P,b,D,N,C,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,b=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),y.push(P*T),y.push(x),y.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(b+h),m.push(P*R+c);for(I=0;I0){for(C=m.length/3,y.push(0),y.push(1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(t*T),y.push(1),y.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(C=m.length/3,y.push(0),y.push(-1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(s*T),y.push(-1),y.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Ti(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=Ti(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Ti(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Di(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Di(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Ti(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Ti(s,this.magFilter)));const a=Ti(s,this.format,this.encoding),l=Ti(s,this.type),h=bi(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class Si extends C{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ye({texture:new Pi({gl:this.scene.canvas.gl}),matrix:p.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=p.vec2([0,0]),this._scale=p.vec2([1,1]),this._rotate=p.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),d.memory.textures++}_checkMinFilter(e){return(e=e||rs)!==ts&&e!==ss&&e!==rs&&e!==es&&e!==$t&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=rs),e}_checkMagFilter(e){return(e=e||ts)!==ts&&e!==Jt&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=ts),e}_checkWrapS(e){return(e=e||Xt)!==Zt&&e!==qt&&e!==Xt&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Xt),e}_checkWrapT(e){return(e=e||Xt)!==Zt&&e!==qt&&e!==Xt&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Xt),e}_checkFlipY(e){return!!e}_checkEncoding(e){return(e=e||ms)!==ms&&e!==ys&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=ms),e}_webglContextRestored(){this._state.texture=new Pi({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,s;0===this._translate[0]&&0===this._translate[1]||(t=p.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=p.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?p.mulMat4(t,s):s),0!==this._rotate&&(s=p.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?p.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Ni(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 s=new Image;s.onload=function(){s=Ni(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.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(),d.memory.textures--}}const xi=d.memory,wi=p.AABB3();class Mi extends gt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ye({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=p.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.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'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Dt.getPositionsBounds(t.positions),o=Dt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new Ne(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),xi.positions+=s.positionsBuf.numItems,p.positions3ToAABB3(t.positions,this._aabb),p.positions3ToAABB3(r,wi,s.positionsDecodeMatrix),p.AABB3ToOBB3(wi,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new Ne(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),xi.colors+=s.colorsBuf.numItems}if(t.uv){const e=Dt.getUVBounds(t.uv),r=Dt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new Ne(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),xi.uvs+=s.uvBuf.numItems}if(t.normals){const e=Dt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new Ne(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),xi.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),xi.indices+=s.indicesBuf.numItems;const o=vt(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),xi.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(),xi.meshes--}}var Bi={};function Fi(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,y=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,b,D,N=0,C=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],u=[],d=[];let f,m,y,g,v,I,_,T,R,P,b,D;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),y=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(y+a),c.push(g+l),c.push(v+h),u.push(1-_/i),u.push(T/r),I=p.normalizeVec3(p.subVec3([y,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,b=(i+1)*(T-1)+_,D=(i+1)*T+_,d.push(R),d.push(P),d.push(b),d.push(b),d.push(D),d.push(R);return E.apply(e,{positions:c,normals:A,uv:u,indices:d})}Bi.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Bi.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Bi.parse._buffToStr(e));window.location.href=s},Bi.clone=function(e){return JSON.parse(JSON.stringify(e))},Bi.bin={},Bi.bin.f=new Float32Array(1),Bi.bin.fb=new Uint8Array(Bi.bin.f.buffer),Bi.bin.rf=function(e,t){for(var s=Bi.bin.f,i=Bi.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},Bi.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Bi.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Bi.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Bi.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Bi.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Bi.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Bi.parse={},Bi.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class Ui extends C{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=p.vec3(t.pos||[0,0,0]),this._up=p.vec3(t.up||[0,1,0]),this._normal=p.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=p.vec3(),this._rtcPos=p.vec3(),this._imageSize=p.vec2(),this._texture=new Si(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 _i(this,{matrix:p.inverseMat4(p.lookAtMat4v(this._pos,p.subVec3(this._pos,this._normal,p.mat4()),this._up,p.mat4())),children:[this._bitmapMesh=new li(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Ot(this,Fi({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Bt(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]}}class Hi extends C{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=p.vec3(),r=V(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),E=Object.entries(y).map((([e,t])=>({color:e,components:t})));o.components.coloring=E;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),o.components.translucency=this._createBCFComponents(t.xrayedObjectIds),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=zi(e.location,Gi),s=zi(e.direction,Gi);h&&p.negateVec3(s),p.subVec3(t,l),r.yUp&&(t=Yi(t),s=Yi(s)),new ui(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),s.push(r++),s.push(r++))})),new Hi(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=zi(e.location,ki),n=zi(e.normal,Vi),a=zi(e.up,ji),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=Yi(o),n=Yi(n),a=Yi(a)),new Ui(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==r.spaces_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&i.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const o=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=zi(e.perspective_camera.camera_view_point,Gi),h=zi(e.perspective_camera.camera_direction,Gi),c=zi(e.perspective_camera.camera_up_vector,Gi),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=zi(e.orthogonal_camera.camera_view_point,Gi),h=zi(e.orthogonal_camera.camera_direction,Gi),c=zi(e.orthogonal_camera.camera_up_vector,Gi),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),p.subVec3(a,l),r.yUp&&(a=Yi(a),h=Yi(h),c=Yi(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:p.addVec3(a,h,Gi)}else h=p.addVec3(a,h,Gi);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=p.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function Wi(e){return{x:e[0],y:e[1],z:e[2]}}function zi(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ki(e){return new Float64Array([e[0],-e[2],e[1]])}function Yi(e){return new Float64Array([e[0],e[2],-e[1]])}const Xi=p.vec3(),Zi=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class qi extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new re(s,t.origin),this._targetMarker=new re(s,t.target),this._originWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new ne(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new oe(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new oe(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new oe(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new oe(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new ae(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new ae(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new ae(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new ae(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,y=s.unitsInfo[m].abbrev;for(var u=0,d=i.length;u{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=t[0]-5+"px",this._markerDiv.style.marginTop=t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),h=e.entity):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class er extends U{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new $i(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,s=e.target,i=new qi(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=0)&&(e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),i=!1))}));let o=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{o=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{o=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{o&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class sr{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 s=this._messages[this._locale];if(!s)return null;const i=ir(e,s);return i?t?rr(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=ir(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=rr(r,[t]),s&&(r=rr(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(e,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new t),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=e;const o=this._events[e];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function ir(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?cr._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(p.subVec3(i.eye,i.look,hr),i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,ar),i.look=p.subVec3(ar,hr,nr)):this._flyingLook&&(i.look=p.lerpVec3(s,0,1,this._look1,this._look2,nr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,lr)):this._flyingEyeLookUp&&(i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,ar),i.look=p.lerpVec3(s,0,1,this._look1,this._look2,nr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,lr)),this._projection2){const t="ortho"===this._projection2?cr._easeOutExpo(e,0,1,1):cr._easeInCubic(e,0,1,1);i.customProjection.matrix=p.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();D.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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=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 Ar extends C{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new cr(this),this._t=0,this.state=Ar.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,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case Ar.SCRUBBING:return;case Ar.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=Ar.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Ar.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=Ar.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=Ar.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=Ar.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=Ar.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=Ar.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Ar.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Ar.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Ar.STOPPED=0,Ar.SCRUBBING=1,Ar.PLAYING=2,Ar.PLAYING_TO=3,p.vec3(),p.vec3(),p.vec3(),p.vec3([0,-1,0]),p.vec4([0,0,0,1]);const ur=p.vec3();class pr{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,s){this.numObjects=0,this._mask=s?E.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,h=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;Tr[0]=s,Tr[1]=i,Tr[2]=t.blendCutoff,Tr[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Tr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===vr[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===vr[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===vr[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?_r:Ir)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class Nr extends Dr{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class Cr extends Nr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Or extends Dr{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class Sr extends Or{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class xr extends Dr{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class wr extends Dr{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class Mr extends Dr{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class Br extends Dr{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class Fr extends Nr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class Lr extends Nr{_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,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles 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;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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 = 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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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("outColor = vColor;"),o.push("}"),o}}class Hr extends Cr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Gr extends Cr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class kr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = vPickColor; "),i.push("}"),i}}class Vr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class jr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),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(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Qr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),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;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Wr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching 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;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class zr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Kr extends Nr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),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); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Yr extends Nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&(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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),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(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals 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;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" 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(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Zr extends Nr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture 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;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),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("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(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("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}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;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e5e6&&(e=5e6),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 eo=p.mat4(),to=p.mat4();function so(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,u=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function oo(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const no=p.vec3(),ao=p.vec3(),lo=p.vec3(),ho=p.vec3(),co=p.mat4();class Ao extends Dr{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=no;let m,y;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=ao;if(l){const e=lo;p.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=G(d,t,co),y=ho,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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()}_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,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${p.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const uo=p.vec3(),po=p.vec3(),fo=p.vec3(),mo=p.vec3(),yo=p.mat4();class Eo extends Dr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=uo;let m,y;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=po;if(l){const e=fo;p.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=G(d,t,yo),y=mo,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_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 s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class go{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Ao(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new Eo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Ao(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Eo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const vo={};const Io=p.mat4(),_o=p.mat4(),To=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.OBB3();const Ro=p.vec3(),Po=p.vec3(),bo=p.vec3(),Do=p.vec3(),No=p.vec3(),Co=p.vec3(),Oo=p.vec3();class So{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._batchingRenderers=function(e){const t=e.id;let s=Jr[t];return s||(s=new qr(e),Jr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=vo[t];return s||(s=new go(e),vo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete vo[t],s._destroy()}))),s}(e.model.scene),this._buffer=new $r(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ye({origin:p.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=p.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=p.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=p.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=p.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Io;y?p.inverseMat4(p.transposeMat4(y,_o),e):p.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,u=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=ro(d,"floor","ceil"),a=oo(n),h=o(d,a),h>c&&(l=n,c=h),n=ro(d,"ceil","ceil"),a=oo(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,r,r.length,v.normals,v.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):so(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=p.mat4());if(e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new Ne(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=Dt.getUVBounds(s.uv),r=Dt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=p.mat3(r.decodeMatrix),e.uvBuf=new Ne(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Ne(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,i,s.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,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;eE)&&(E=e,i.set(g),r&&p.triangleNormal(d,f,m,r),y=!0)}}return y&&r&&(p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),y}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 xo extends Or{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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=s.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing 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;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class wo extends Or{_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,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),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 {"),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("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,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,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// 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 vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Bo extends Sr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Fo extends Sr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != 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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.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);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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("outColor = vColor;"),i.push("}"),i}}class Lo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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("outColor = vPickColor; "),i.push("}"),i}}class Uo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),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;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry 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;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Ho extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),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(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Go extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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),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;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer 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"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class ko extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 Vo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),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,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.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);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),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; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 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(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class jo extends Or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const Qo={3e3:"linearToLinear",3001:"sRGBToLinear"};class Wo extends Or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.getNumAllocatedSectionPlanes()>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e0&&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("}"),i.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 = "+Qo[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Qo[i.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;")),i.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=s.getNumAllocatedSectionPlanes();e (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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals 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,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),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(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals 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;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(" 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(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Ko extends Or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),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 mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),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; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.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 );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(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;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return 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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),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(${p.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sn=p.vec3(),rn=p.vec3(),on=p.vec3(),nn=p.vec3(),an=p.mat4();class ln extends Dr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=sn;let m,y;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=rn;if(l){const e=p.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]+=h[0],t[1]+=h[1],t[2]+=h[2],m=G(d,t,an),y=nn,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let E=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,E+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,E+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,E+=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),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(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.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_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,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),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),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),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("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer 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"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class hn{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new tn(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new ln(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new tn(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new ln(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const cn={};const An=new Uint8Array(4),un=new Float32Array(1),pn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]);const dn=new Float32Array(3),fn=p.vec3(),mn=p.vec3(),yn=p.vec3(),En=p.vec3(),gn=p.vec3(),vn=p.vec3(),In=p.vec3(),_n=new Float32Array(4);class Tn{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Xo[t];return s||(s=new Yo(e),Xo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Xo[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=cn[t];return s||(s=new hn(e),cn[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete cn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ye({numInstances:0,obb:p.OBB3(),origin:p.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=p.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Ne(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new Ne(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new Ne(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=p.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Ne(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Ne(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Ne(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Ne(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Ne(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(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,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";An[0]=t[0],An[1]=t[1],An[2]=t[2],An[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(An,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&Q),r=!!(t&X),o=!!(t&Z),n=!!(t&q),a=!!(t&J),l=!!(t&z),h=!!(t&W);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?vr.NOT_RENDERED:s?vr.COLOR_TRANSPARENT:vr.COLOR_OPAQUE,A=!i||h?vr.NOT_RENDERED:n?vr.SILHOUETTE_SELECTED:o?vr.SILHOUETTE_HIGHLIGHTED:r?vr.SILHOUETTE_XRAYED:vr.NOT_RENDERED;let u=0;u=!i||h?vr.NOT_RENDERED:n?vr.EDGES_SELECTED:o?vr.EDGES_HIGHLIGHTED:r?vr.EDGES_XRAYED:a?s?vr.EDGES_COLOR_TRANSPARENT:vr.EDGES_COLOR_OPAQUE:vr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?vr.PICK:vr.NOT_RENDERED)<<12,p|=(t&K?1:0)<<16,un[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(un,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(dn[0]=t[0],dn[1]=t[1],dn[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(dn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=pn,u=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&p.triangleNormal(f,m,y,r),E=!0)}}return E&&r&&(p.transformVec3(a.normalMatrix,r,r),p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),E}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 Rn extends Mr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Pn extends Mr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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;"),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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class bn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Rn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pn(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Dn={};class Nn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.OBB3();class Cn{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Dn[t];return s||(s=new bn(e),Dn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Dn[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new Nn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ye({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=p.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=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=so(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new Ne(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),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 {"),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, float(color.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 = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 Sn extends Br{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Lines 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 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),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 = 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;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class xn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new On(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Sn(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const wn={};const Mn=new Uint8Array(4),Bn=new Float32Array(1);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]);const Fn=new Float32Array(3),Ln=new Float32Array(4);class Un{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=wn[t];return s||(s=new xn(e),wn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete wn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ye({obb:p.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=p.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=p.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Ne(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(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,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Mn[0]=t[0],Mn[1]=t[1],Mn[2]=t[2],Mn[3]=t[3],this._state.colorsBuf.setData(Mn,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&Q),r=!!(t&X),o=!!(t&Z),n=!!(t&q),a=!!(t&J),l=!!(t&z),h=!!(t&W);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?vr.NOT_RENDERED:s?vr.COLOR_TRANSPARENT:vr.COLOR_OPAQUE,A=!i||h?vr.NOT_RENDERED:n?vr.SILHOUETTE_SELECTED:o?vr.SILHOUETTE_HIGHLIGHTED:r?vr.SILHOUETTE_XRAYED:vr.NOT_RENDERED;let u=0;u=!i||h?vr.NOT_RENDERED:n?vr.EDGES_SELECTED:o?vr.EDGES_HIGHLIGHTED:r?vr.EDGES_XRAYED:a?s?vr.EDGES_COLOR_TRANSPARENT:vr.EDGES_COLOR_OPAQUE:vr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?vr.PICK:vr.NOT_RENDERED)<<12,p|=(t&K?255:0)<<16,Bn[0]=p,this._state.flagsBuf.setData(Bn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Fn[0]=t[0],Fn[1]=t[1],Fn[2]=t[2],this._state.offsetsBuf.setData(Fn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;Ln[0]=t[0],Ln[1]=t[4],Ln[2]=t[8],Ln[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ln,s),Ln[0]=t[1],Ln[1]=t[5],Ln[2]=t[9],Ln[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ln,s),Ln[0]=t[2],Ln[1]=t[6],Ln[2]=t[10],Ln[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ln,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}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 Hn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Gn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 kn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class Vn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class jn extends xr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Qn{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Hn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Gn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new kn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new jn(this._scene)),this._occlusionRenderer}_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()}}const Wn={};class zn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}p.vec4(),p.vec4(),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.OBB3();class Kn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=Wn[t];return s||(s=new Qn(e),Wn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Wn[t],s._destroy()}))),s}(e.model.scene),this._buffer=new zn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ye({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=p.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=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=so(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new Ne(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new Ne(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Xn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class Zn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class qn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Jn extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class $n extends wr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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;"),s=0,i=t.getNumAllocatedSectionPlanes();s 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 ea extends wr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),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;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),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("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),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 = 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 = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class ta{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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Xn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new $n(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new qn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Jn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ea(this._scene)),this._shadowRenderer}_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()}}const sa={};const ia=new Uint8Array(4),ra=new Float32Array(1);p.vec4([0,0,0,1]),p.vec4([0,0,0,1]),p.vec4([0,0,0,1]);const oa=new Float32Array(3),na=new Float32Array(4);class aa{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=sa[t];return s||(s=new ta(e),sa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete sa[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ye({obb:p.OBB3(),numInstances:0,origin:e.origin?p.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=p.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){p.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let i=!1;s.flagsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new Ne(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=p.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new Ne(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new Ne(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new Ne(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;s.pickColorsBuf=new Ne(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Z&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&q&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(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,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";ia[0]=t[0],ia[1]=t[1],ia[2]=t[2],this._state.colorsBuf.setData(ia,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&Q),r=!!(t&X),o=!!(t&Z),n=!!(t&q),a=!!(t&J),l=!!(t&z),h=!!(t&W);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?vr.NOT_RENDERED:s?vr.COLOR_TRANSPARENT:vr.COLOR_OPAQUE,A=!i||h?vr.NOT_RENDERED:n?vr.SILHOUETTE_SELECTED:o?vr.SILHOUETTE_HIGHLIGHTED:r?vr.SILHOUETTE_XRAYED:vr.NOT_RENDERED;let u=0;u=!i||h?vr.NOT_RENDERED:n?vr.EDGES_SELECTED:o?vr.EDGES_HIGHLIGHTED:r?vr.EDGES_XRAYED:a?s?vr.EDGES_COLOR_TRANSPARENT:vr.EDGES_COLOR_OPAQUE:vr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?vr.PICK:vr.NOT_RENDERED)<<12,p|=(t&K?255:0)<<16,ra[0]=p,this._state.flagsBuf.setData(ra,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(oa[0]=t[0],oa[1]=t[1],oa[2]=t[2],this._state.offsetsBuf.setData(oa,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;na[0]=t[0],na[1]=t[4],na[2]=t[8],na[3]=t[12],this._state.modelMatrixCol0Buf.setData(na,s),na[0]=t[1],na[1]=t[5],na[2]=t[9],na[3]=t[13],this._state.modelMatrixCol1Buf.setData(na,s),na[0]=t[2],na[1]=t[6],na[2]=t[10],na[3]=t[14],this._state.modelMatrixCol2Buf.setData(na,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,vr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,vr.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._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,vr.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,vr.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,vr.PICK)}drawPickNormals(e,t){}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()}}class la{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class ha{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const ca={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={}}};const Aa=new class{constructor(e,t,s){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=s}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,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==ua[e])return void ua[e].push({onLoad:t,onProgress:s,onError:i});ua[e]=[],ua[e].push({onLoad:t,onProgress:s,onError:i});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 s=ua[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.length;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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{ca.add(e,t);const s=ua[e];delete ua[e];for(let e=0,i=s.length;e{const s=ua[e];if(void 0===s)throw this.manager.itemError(e),t;delete ua[e];for(let e=0,i=s.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class da{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{const i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let fa=0;class ma{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new da,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new pa;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new pa;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=ma.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(ma.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(ma.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(ma.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),fa>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),fa++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?ts:is,magFilter:1===o.length?ts:is,encoding:2===A?ys:ms,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),fa--}}ma.BasisFormat={ETC1S:0,UASTC_4x4:1},ma.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},ma.EngineFormat={RGBAFormat:os,RGBA_ASTC_4x4_Format:ds,RGBA_BPTC_Format:fs,RGBA_ETC2_EAC_Format:ps,RGBA_PVRTC_4BPPV1_Format:As,RGBA_S3TC_DXT5_Format:hs,RGB_ETC1_Format:36196,RGB_ETC2_Format:us,RGB_PVRTC_4BPPV1_Format:cs,RGB_S3TC_DXT1_Format:ns},ma.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),y=n.getDFDFlags(),{transcoderFormat:E,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i