@xeokit/xeokit-sdk 2.6.82 → 2.6.83-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  /**
2
- * xeokit-sdk v2.6.82
3
- * Commit: 80a64586da2504c5e8c25befca093df18a63efaa
4
- * Built: 2025-07-02T14:23:42.465Z
2
+ * xeokit-sdk v2.6.83-beta.2
3
+ * Commit: 9359e201c147be9d06d909031acbc1e499ee408d
4
+ * Built: 2025-07-08T07:51:00.010Z
5
5
  */
6
6
 
7
7
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}let o=!0,n=o?Float64Array:Float32Array;const a=new n(3),l=new n(16),A=new n(16),c=new n(4),h={setDoublePrecisionEnabled(e){o=e,n=o?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(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 n(e||16),mat4ToMat3:(e,t=new n(9))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t),doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r<o;r++)h.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble(e,t){const i=n.from([e])[0],s=e-i;t[0]=i,t[1]=s},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],compareVec4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i<e.length;i++)t[0]+=e[i][0],t[1]+=e[i][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>h.dotVec4(e,e),lenVec4:e=>Math.sqrt(h.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=>h.dotVec3(e,e),sqLenVec2:e=>h.dotVec2(e,e),lenVec3:e=>Math.sqrt(h.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>h.lenVec3(h.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(h.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>h.lenVec2(h.subVec2(t,i,e))})(),rcpVec3:(e,t)=>h.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/h.lenVec4(e);return h.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/h.lenVec3(e);return h.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/h.lenVec2(e);return h.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=h.dotVec3(e,t)/Math.sqrt(h.sqLenVec3(e)*h.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=h.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=h.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=h.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i<s;i++)t[i]=e(t[i]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||h.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:()=>h.m4s(0),setMat4ToOnes:()=>h.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>h.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>h.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(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 n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>h.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],_=e[15],v=t[0],b=t[1],y=t[2],w=t[3],B=t[4],x=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],T=t[12],D=t[13],S=t[14],R=t[15];return i[0]=v*s+b*a+y*h+w*f,i[1]=v*r+b*l+y*u+w*m,i[2]=v*o+b*A+y*d+w*g,i[3]=v*n+b*c+y*p+w*_,i[4]=B*s+x*a+P*h+C*f,i[5]=B*r+x*l+P*u+C*m,i[6]=B*o+x*A+P*d+C*g,i[7]=B*n+x*c+P*p+C*_,i[8]=M*s+F*a+E*h+I*f,i[9]=M*r+F*l+E*u+I*m,i[10]=M*o+F*A+E*d+I*g,i[11]=M*n+F*c+E*p+I*_,i[12]=T*s+D*a+S*h+R*f,i[13]=T*r+D*l+S*u+R*m,i[14]=T*o+D*A+S*d+R*g,i[15]=T*n+D*c+S*p+R*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],c=e[2],h=e[5],u=e[8],d=t[0],p=t[3],f=t[6],m=t[1],g=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*m+o*v,i[3]=s*p+r*g+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*m+A*v,i[4]=a*p+l*g+A*b,i[7]=a*f+l*_+A*y,i[2]=c*d+h*m+u*v,i[5]=c*p+h*g+u*b,i[8]=c*f+h*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=h.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],c=e[6],h=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=s,e[12]=A,e[13]=h,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],c=e[9],h=e[10],u=e[11],d=e[12],p=e[13],f=e[14],m=e[15];return d*c*a*r-A*p*a*r-d*n*h*r+o*p*h*r+A*n*f*r-o*c*f*r-d*c*s*l+A*p*s*l+d*i*h*l-t*p*h*l-A*i*f*l+t*c*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*m+o*c*s*m+A*i*a*m-t*c*a*m-o*i*h*m+t*n*h*m},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],c=e[8],h=e[9],u=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,w=s*A-o*a,B=r*A-o*l,x=c*f-h*p,P=c*m-u*p,C=c*g-d*p,M=h*m-u*f,F=h*g-d*f,E=u*g-d*m,I=1/(_*E-v*F+b*M+y*C-w*P+B*x);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*B-m*w+g*y)*I,t[3]=(-h*B+u*w-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*B+m*b-g*v)*I,t[7]=(c*B-u*b+d*v)*I,t[8]=(n*F-a*C+A*x)*I,t[9]=(-i*F+s*C-o*x)*I,t[10]=(p*w-f*b+g*_)*I,t[11]=(-c*w+h*b-d*_)*I,t[12]=(-n*M+a*P-l*x)*I,t[13]=(i*M-s*P+r*x)*I,t[14]=(-p*y+f*v-m*_)*I,t[15]=(c*y-h*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||h.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||h.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,h.translationMat4v(e,r))})(),translationMat4s:(e,t)=>h.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>h.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=h.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let c,u,d,p,f,m;return c=a*l,u=l*A,d=A*a,p=a*r,f=l*r,m=A*r,(i=i||h.mat4())[0]=n*a*a+o,i[1]=n*c+m,i[2]=n*d-f,i[3]=0,i[4]=n*c-m,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>h.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=h.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=h.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,h.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>h.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=h.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,c=s*a,u=s*l,d=s*A,p=r*l,f=r*A,m=o*A,g=n*a,_=n*l,v=n*A;return i[0]=1-(p+m),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(c+m),i[6]=f+g,i[7]=0,i[8]=d+_,i[9]=f-g,i[10]=1-(c+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=h.vec4()){const s=h.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],c=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-c,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i[0]*=h.RADTODEG,i[1]*=h.RADTODEG,i[2]*=h.RADTODEG,i},composeMat4:(e,t,i,s=h.mat4())=>(h.quaternionToRotationMat4(t,s),h.scaleMat4v(i,s),h.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=h.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=h.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=h.lenVec3(e);h.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,c=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=u,t[9]*=u,t[10]*=u,h.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=h.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],c=t[0],u=t[1],d=t[2];if(r===c&&o===u&&n===d)return h.identityMat4();let p,f,m,g,_,v,b,y,w,B;return p=r-c,f=o-u,m=n-d,B=1/Math.sqrt(p*p+f*f+m*m),p*=B,f*=B,m*=B,g=l*m-A*f,_=A*p-a*m,v=a*f-l*p,B=Math.sqrt(g*g+_*_+v*v),B?(B=1/B,g*=B,_*=B,v*=B):(g=0,_=0,v=0),b=f*v-m*_,y=m*g-p*v,w=p*_-f*g,B=Math.sqrt(b*b+y*y+w*w),B?(B=1/B,b*=B,y*=B,w*=B):(b=0,y=0,w=0),s[0]=g,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=w,s[10]=m,s[11]=0,s[12]=-(g*r+_*o+v*n),s[13]=-(b*r+y*o+w*n),s[14]=-(p*r+f*o+m*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>h.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=h.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=h.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];h.addVec4(r,s,l),h.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],c=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/c,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/c,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=h.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],h.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=h.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=h.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],c=e[1],h=e[2],u=e[3],d=e[4],p=e[5],f=e[6],m=e[7],g=e[8],_=e[9],v=e[10],b=e[11],y=e[12],w=e[13],B=e[14],x=e[15];let P;for(let e=0;e<r;++e)l=t[e],o=l[0],n=l[1],a=l[2],P=s[e]||(s[e]=[0,0,0]),P[0]=A*o+d*n+g*a+y,P[1]=c*o+p*n+_*a+w,P[2]=h*o+f*n+v*a+B,P[3]=u*o+m*n+b*a+x;return s.length=r,s},transformPositions3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2];e[3];const h=e[4],u=e[5],d=e[6];e[7];const p=e[8],f=e[9],m=e[10];e[11];const g=e[12],_=e[13],v=e[14];for(e[15],s=0;s<r;s+=3)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+h*n+p*a+g,i[s+1]=A*o+u*n+f*a+_,i[s+2]=c*o+d*n+m*a+v;return i},transformPositions4(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2],h=e[3],u=e[4],d=e[5],p=e[6],f=e[7],m=e[8],g=e[9],_=e[10],v=e[11],b=e[12],y=e[13],w=e[14],B=e[15];for(s=0;s<r;s+=4)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+u*n+m*a+b,i[s+1]=A*o+d*n+g*a+y,i[s+2]=c*o+p*n+_*a+w,i[s+3]=h*o+f*n+v*a+B;return i},transformVec3(e,t,i){const s=t[0],r=t[1],o=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*o,i[1]=e[1]*s+e[5]*r+e[9]*o,i[2]=e[2]*s+e[6]*r+e[10]*o,i},transformVec4(e,t,i){const s=t[0],r=t[1],o=t[2],n=t[3];return(i=i||h.vec4())[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},rotateVec2(e,t,i,s=e){const r=Math.cos(i),o=Math.sin(i),n=e[0]-t[0],a=e[1]-t[1];return s[0]=n*r-a*o+t[0],s[1]=n*o+a*r+t[1],e},rotateVec3X(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0],o[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),o[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Y(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),o[1]=r[1],o[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Z(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),o[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),o[2]=r[2],s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},projectVec4(e,t){const i=1/e[3];return(t=t||h.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(()=>{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||h.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||h.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i<s;i++)for(n=e[i],r=0,o=n.length;r<o;r++)t.push(n[r]);return t},identityQuaternion:(e=h.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=h.vec4()){const s=e[0]*h.DEGTORAD/2,r=e[1]*h.DEGTORAD/2,o=e[2]*h.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),c=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*c*u,i[1]=n*c*l-A*a*u,i[2]=n*a*u+A*c*l,i[3]=n*a*l-A*c*u):"YXZ"===t?(i[0]=A*a*l+n*c*u,i[1]=n*c*l-A*a*u,i[2]=n*a*u-A*c*l,i[3]=n*a*l+A*c*u):"ZXY"===t?(i[0]=A*a*l-n*c*u,i[1]=n*c*l+A*a*u,i[2]=n*a*u+A*c*l,i[3]=n*a*l-A*c*u):"ZYX"===t?(i[0]=A*a*l-n*c*u,i[1]=n*c*l+A*a*u,i[2]=n*a*u-A*c*l,i[3]=n*a*l+A*c*u):"YZX"===t?(i[0]=A*a*l+n*c*u,i[1]=n*c*l+A*a*u,i[2]=n*a*u-A*c*l,i[3]=n*a*l-A*c*u):"XZY"===t&&(i[0]=A*a*l-n*c*u,i[1]=n*c*l-A*a*u,i[2]=n*a*u+A*c*l,i[3]=n*a*l+A*c*u),i},mat4ToQuaternion(e,t=h.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],c=e[10];let u;const d=i+n+c;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>c?(u=2*Math.sqrt(1+i-n-c),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>c?(u=2*Math.sqrt(1+n-i-c),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+c-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=h.vec4()){const s=Math.sqrt(h.dotVec3(e,e)*h.dotVec3(t,t));let r=s+h.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):h.cross3Vec3(e,t,i),i[3]=r,h.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=h.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||h.vec3(),h.quaternionToRotationMat4(t,e),h.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=h.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],c=t[3];return i[0]=n*a+s*c+r*A-o*l,i[1]=n*l+r*c+o*a-s*A,i[2]=n*A+o*c+s*l-r*a,i[3]=n*c-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=h.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],c=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=c*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-c*-l,i[2]=d*A+p*-l+c*-a-u*-n,i},quaternionToMat4(e,t){t=h.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,c=a*o,u=l*o,d=n*i,p=a*i,f=l*i,m=a*s,g=l*s,_=l*r;return t[0]=1-(m+_),t[1]=p+u,t[2]=f-c,t[4]=p-u,t[5]=1-(d+_),t[6]=g+A,t[8]=f+c,t[9]=g-A,t[10]=1-(d+m),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,c=i*a,h=i*l,u=s*a,d=s*l,p=r*l,f=o*n,m=o*a,g=o*l;return t[0]=1-(u+p),t[4]=c-g,t[8]=h+m,t[1]=c+g,t[5]=1-(A+p),t[9]=d-f,t[2]=h-m,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=h.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>h.normalizeQuaternion(h.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=h.vec4()){const i=(e=h.normalizeQuaternion(e,c))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2],h=e[3],u=e[4],d=e[5],p=e[6],f=e[7],m=e[8],g=e[9],_=e[10],v=e[11],b=e[12],y=e[13],w=e[14],B=e[15];for(s=0;s<r;s+=4)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+u*n+m*a+b,i[s+1]=A*o+d*n+g*a+y,i[s+2]=c*o+p*n+_*a+w,i[s+3]=h*o+f*n+v*a+B;return i},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],h.subVec3(t,e,i),Math.abs(h.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=h.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],c=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=c>u?c:u,Math.abs(h.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||h.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||h.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=h.AABB3())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MAX_DOUBLE,e[3]=h.MIN_DOUBLE,e[4]=h.MIN_DOUBLE,e[5]=h.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=h.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 n(3);return(t,i,s)=>{i=i||h.AABB3();let r,o,n,a=h.MAX_DOUBLE,l=h.MAX_DOUBLE,A=h.MAX_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE,d=h.MIN_DOUBLE;for(let i=0,p=t.length;i<p;i+=3)s?(e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2],h.decompressPosition(e,s,e),r=e[0],o=e[1],n=e[2]):(r=t[i+0],o=t[i+1],n=t[i+2]),r<a&&(a=r),o<l&&(l=o),n<A&&(A=n),r>c&&(c=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=c,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=h.AABB3()){let i,s,r,o=h.MAX_DOUBLE,n=h.MAX_DOUBLE,a=h.MAX_DOUBLE,l=h.MIN_DOUBLE,A=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)i=e[t+0],s=e[t+1],r=e[t+2],i<o&&(o=i),s<n&&(n=s),r<a&&(a=r),i>l&&(l=i),s>A&&(A=s),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=c,t},points3ToAABB3(e,t=h.AABB3()){let i,s,r,o=h.MAX_DOUBLE,n=h.MAX_DOUBLE,a=h.MAX_DOUBLE,l=h.MIN_DOUBLE,A=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)i=e[t][0],s=e[t][1],r=e[t][2],i<o&&(o=i),s<n&&(n=s),r<a&&(a=r),i>l&&(l=i),s>A&&(A=s),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=c,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||h.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;s<a;s++)r+=t[s][0],o+=t[s][1],n+=t[s][2];i[0]=r/a,i[1]=o/a,i[2]=n/a;let l,A=0;for(s=0;s<a;s++)l=Math.abs(h.lenVec3(h.subVec3(t[s],i,e))),l>A&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||h.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;r<l;r+=3)o+=i[r],n+=i[r+1],a+=i[r+2];const c=l/3;let u;for(s[0]=o/c,s[1]=n/c,s[2]=a/c,r=0;r<l;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],u=Math.abs(h.lenVec3(h.subVec3(e,s,t))),u>A&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||h.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;r<l;r+=4)o+=i[r+0],n+=i[r+1],a+=i[r+2];s[0]=o/A,s[1]=n/A,s[2]=a/A;let c,u=0;for(r=0;r<l;r+=4)e[0]=i[r+0],e[1]=i[r+1],e[2]=i[r+2],c=Math.abs(h.lenVec3(h.subVec3(e,s,t))),c>u&&(u=c);return s[3]=u,s}})(),getSphere3Center:(e,t=h.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=h.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o<n;o+=3)i+=e[o+0],s+=e[o+1],r+=e[o+2];const a=e.length/3;return t[0]=i/a,t[1]=s/a,t[2]=r/a,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var i,s,r,o=0,n=t.length;o<n;o+=3)i=t[o],s=t[o+1],r=t[o+2],e[0]>i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]<i&&(e[3]=i),e[4]<s&&(e[4]=s),e[5]<r&&(e[5]=r);return e},collapseAABB2:(e=h.AABB2())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MIN_DOUBLE,e[3]=h.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],point3AABB3AbsoluteIntersect:(e,t)=>e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2],planeAABB3Intersect(e,t,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=h.AABB2()){let i,s,r,o,n=h.MAX_DOUBLE,a=h.MAX_DOUBLE,l=h.MIN_DOUBLE,A=h.MIN_DOUBLE;for(let t=0,c=e.length;t<c;t+=4)i=e[t+0],s=e[t+1],r=e[t+3]||1,o=1/r,i*=o,s*=o,i<n&&(n=i),s<a&&(a=s),i>l&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,i,s=e){const r=.5*(e[0]+1),o=.5*(e[1]+1),n=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(n*t),s[3]=i-Math.floor(o*i),s},tangentQuadraticBezier:(e,t,i,s)=>2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=h.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],c=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(c*c+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,c)=>{c=c||h.vec3();const u=h.subVec3(l,a,e),d=h.subVec3(A,a,t),p=h.cross3Vec3(n,d,i),f=h.dotVec3(u,p);if(f<1e-6)return null;const m=h.subVec3(o,a,s),g=h.dotVec3(m,p);if(g<0||g>f)return null;const _=h.cross3Vec3(m,u,r),v=h.dotVec3(n,_);if(v<0||g+v>f)return null;const b=h.dotVec3(d,_)/f;return c[0]=o[0]+b*n[0],c[1]=o[1]+b*n[1],c[2]=o[2]+b*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||h.vec3(),o=h.normalizeVec3(o,e);const c=h.subVec3(a,n,t),u=h.subVec3(l,n,i),d=h.cross3Vec3(c,u,s);h.normalizeVec3(d,d);const p=-h.dotVec3(n,d),f=-(h.dotVec3(r,d)+p)/h.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=h.subVec3(n,r,e),A=h.subVec3(o,r,t),c=h.subVec3(s,r,i),u=h.dotVec3(l,l),d=h.dotVec3(l,A),p=h.dotVec3(l,c),f=h.dotVec3(A,A),m=h.dotVec3(A,c),g=u*f-d*d;if(0===g)return null;const _=1/g,v=(f*p-d*m)*_,b=(u*m-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=h.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let c,h,u,d;const p=1e4;let f,m,g=0;for(f=0,m=e.length;f<m;f+=3)c=e[f],h=e[f+1],u=e[f+2],d=`${Math.round(c*p)}_${Math.round(h*p)}_${Math.round(u*p)}`,void 0===r[d]&&(r[d]=n.length/3,n.push(c),n.push(h),n.push(u),t&&(a.push(t[f]),a.push(t[f+1]),a.push(t[f+2])),i&&(l.push(i[g]),l.push(i[g+1]))),o[f/3]=r[d],g+=2;for(f=0,m=s.length;f<m;f++)A[f]=o[s[f]];const _={positions:n,indices:A};return a&&(_.normals=a),l&&(_.uv=l),_},buildNormals:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,c;const u=new Array(n.length/3);let d,p,f,m,g,_,v;for(A=0,c=a.length;A<c;A+=3){d=a[A],p=a[A+1],f=a[A+2],e[0]=n[3*d],e[1]=n[3*d+1],e[2]=n[3*d+2],t[0]=n[3*p],t[1]=n[3*p+1],t[2]=n[3*p+2],i[0]=n[3*f],i[1]=n[3*f+1],i[2]=n[3*f+2],h.subVec3(t,e,s),h.subVec3(i,e,r);const l=h.vec3();h.normalizeVec3(h.cross3Vec3(s,r,o),l),u[d]||(u[d]=[]),u[p]||(u[p]=[]),u[f]||(u[f]=[]),u[d].push(l),u[p].push(l),u[f].push(l)}for(l=l&&l.length===n.length?l:new Float32Array(n.length),A=0,c=u.length;A<c;A++){m=u[A].length,g=0,_=0,v=0;for(let e=0;e<m;e++)g+=u[A][e][0],_+=u[A][e][1],v+=u[A][e][2];l[3*A]=g/m,l[3*A+1]=_/m,l[3*A+2]=v/m}return l}})(),buildTangents:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const c=new Float32Array(n.length);for(let u=0;u<l.length;u+=3){let d=l[u];const p=n.subarray(3*d,3*d+3),f=A.subarray(2*d,2*d+2);d=l[u+1];const m=n.subarray(3*d,3*d+3),g=A.subarray(2*d,2*d+2);d=l[u+2];const _=n.subarray(3*d,3*d+3),v=A.subarray(2*d,2*d+2),b=h.subVec3(m,p,e),y=h.subVec3(_,p,t),w=h.subVec2(g,f,i),B=h.subVec2(v,f,s),x=1/(w[0]*B[1]-w[1]*B[0]),P=h.mulVec3Scalar(h.subVec3(h.mulVec3Scalar(b,B[1],r),h.mulVec3Scalar(y,w[1],o),a),x,o);let C;for(let e=0;e<3;e++)C=3*l[u+e],c[C]+=P[0],c[C+1]+=P[1],c[C+2]+=P[2]}return c}})(),buildPickTriangles(e,t,i){const s=t.length,r=i?new Uint16Array(9*s):new Float32Array(9*s),o=new Uint8Array(12*s);let n,a,l,A,c,h,u=0,d=0,p=0;for(let i=0;i<s;i+=3)h=u>>24&255,c=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,c,u;const d=1e4;let p,f,m,g,_,v;for(f=0,g=e.length;f<g;f+=3){p=f/3,l=e[f],A=e[f+1],c=e[f+2],u=`${Math.round(l*d)}_${Math.round(A*d)}_${Math.round(c*d)}`,void 0===r[u]?r[u]=[p]:r[u].push(p);const i=h.normalizeVec3([t[f],t[f+1],t[f+2]]);o[p]=i,a=h.vec4([i[0],i[1],i[2],1]),n[p]=a}for(u in r)if(r.hasOwnProperty(u)){const e=r[u],t=e.length;for(f=0;f<t;f++){const i=e[f];for(a=n[i],m=0;m<t;m++){if(f===m)continue;const t=e[m];_=o[i],v=o[t];Math.abs(h.angleVec3(_,v)/h.DEGTORAD)<s&&(a[0]+=v[0],a[1]+=v[1],a[2]+=v[2],a[3]+=1)}}}for(f=0,g=t.length;f<g;f+=3)a=n[f/3],t[f+0]=a[0]/a[3],t[f+1]=a[1]/a[3],t[f+2]=a[2]/a[3]},transformRay:(()=>{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,h.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],h.transformVec3(i,e,t),h.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(4),i=new n(4),s=(t,i,s,r,o)=>{o[0]=t,o[1]=i,o[2]=s,o[3]=1,h.transformVec4(e,o,o),r||h.mulVec4Scalar(o,1/o[3])};return(r,o,n,a,l,A,c)=>{const u="ortho"===a;h.mulMat4(n,o,e),h.inverseMat4(e,e);const d=2*l[0]/r.clientWidth-1,p=1-2*l[1]/r.clientHeight;s(d,p,-1,u,t),s(d,p,1,u,i),A[0]=t[0],A[1]=t[1],A[2]=t[2],h.subVec3(i,t,c),h.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l,A)=>{h.canvasPosToWorldRay(i,s,r,o,a,e,t),h.worldRayToLocalRay(n,e,t,l,A)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=h.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,h.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],h.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,c;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,c=i.length;A<c;++A){var h=3*i[A];for(let e=0;e<3;++e){const t=3*s[h+e];r[t]<a[0]&&(a[0]=r[t]),r[t]>a[3]&&(a[3]=r[t]),r[t+1]<a[1]&&(a[1]=r[t+1]),r[t+1]>a[4]&&(a[4]=r[t+1]),r[t+2]<a[2]&&(a[2]=r[t+2]),r[t+2]>a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const m=new Array(i.length);let g=0;for(A=0,c=i.length;A<c;++A){const e=s[h=3*i[A]],t=3*s[h+1],o=3*s[h+2];r[3*e+u]<=d||r[t+u]<=d||r[o+u]<=d?p[f++]=i[A]:m[g++]=i[A]}return p.length=f,m.length=g,l.left=t(p,s,r,o+1),l.right=t(m,s,r,o+1),l}return(e,i)=>{const s=e.length/3,r=new Array(s);for(let e=0;e<s;++e)r[e]=e;return t(r,e,i,0)}})(),decompressPosition(e,t,i){(i=i||e)[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},octDecodeVec2(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const n=1-Math.abs(r)-Math.abs(o);n<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};h.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=h.vec3(),c=h.vec3(),u=h.vec3(),d=h.vec3(),p=h.vec3(),f=h.vec3(),m=h.vec3();return function(g,_,v,b){!function(r,o){const n={};let a,l,A,c;const h=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;u<d;u+=3)a=r[u],l=r[u+1],A=r[u+2],c=Math.round(a*h)+"_"+Math.round(l*h)+"_"+Math.round(A*h),void 0===n[c]&&(n[c]=p/3,e[p++]=a,e[p++]=l,e[p++]=A),t[u/3]=n[c];for(u=0,d=o.length;u<d;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,_),function(t,i){o=0;for(let g=0,_=t;g<_;g+=3){const t=3*s[g],_=3*s[g+1],v=3*s[g+2];i?(n[0]=e[t],n[1]=e[t+1],n[2]=e[t+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(n,i,A),h.decompressPosition(a,i,c),h.decompressPosition(l,i,u)):(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],u[0]=e[v],u[1]=e[v+1],u[2]=e[v+2]),h.subVec3(u,c,d),h.subVec3(A,c,p),h.cross3Vec3(d,p,f),h.normalizeVec3(f,m);const b=r[o]||(r[o]={normal:h.vec3()});b.normal[0]=m[0],b.normal[1]=m[1],b.normal[2]=m[2],o++}}(_.length,v);const y=[],w=Math.cos(h.DEGTORAD*b),B={};let x,P,C,M,F,E,I,T,D,S,R,U=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)x=s[e+i],P=s[e+(i+1)%3],C=Math.min(x,P),M=Math.max(x,P),F=C+","+M,void 0===B[F]?B[F]={index1:C,index2:M,face1:t,face2:void 0}:B[F].face2=t}for(F in B)E=B[F],void 0!==E.face2&&(I=r[E.face1].normal,T=r[E.face2].normal,D=h.dotVec3(I,T),D>w)||(S=i[E.index1],R=i[E.index2],(!U&&S>65535||R>65535)&&(U=!0),y.push(S),y.push(R));return U?new Uint32Array(y):new Uint16Array(y)}}(),h.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r<o;r+=s){if(a[0]=i[r+0]-e[0],a[1]=i[r+1]-e[1],a[2]=i[r+2]-e[2],a[0]*t[0]+a[1]*t[1]+a[2]*t[2]<0)return!0}return!1};const u=new Float32Array(3);class d{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const p={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r<s;++r)t.push(r);return String.fromCharCode.apply(null,t)})).join("");function m(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return f.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const g=function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var s=t[i].split("=");if(void 0===e[s[0]])e[s[0]]=decodeURIComponent(s[1]);else if("string"==typeof e[s[0]]){var r=[e[s[0]],decodeURIComponent(s[1])];e[s[0]]=r}else e[s[0]].push(decodeURIComponent(s[1]))}return e}();const _={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var s=t.nodeValue;if(null===s.match(/^\s+$/))return s}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var r={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var o=0;o<t.attributes.length;o++){var n=t.attributes[o];r[i[n.nodeName]||n.nodeName]=n.nodeValue}for(var a=0;a<t.childNodes.length;a++){(o=e(t.childNodes[a],i))&&r.children.push(o)}return r}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return m(t[0],2)+[1,4,7,10,13].map((function(e){return m((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[],s=function(e){e.type===t&&i.push(e),(e.children||[]).forEach((function(e){s(e)}))};return s(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(e){4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)}))},loadJSON:function(e,t,i){var s=e=>{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n<o.length;n++)i[n]=o.charCodeAt(n);M.scheduleTask((()=>{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:g,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r<o;r++){s[r].parent=i.id,e(s[r])}i.children=[]}(e),t}},v={},b=new e,y=new d,w={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},B=[];let x,P=0,C=0;const M=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(M.scenes[e.id])return void console.error(`[ERROR] Scene ${_.inQuotes(e.id)} already exists`)}else e.id=b.addItem({});M.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;v[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},p.components.scenes++,e.once("destroyed",(()=>{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s<e);)t=y.shift(),i=y.shift(),i?t.call(i):t(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return y.length}},F=function(){let e=Date.now();if(x=e-P,P>0&&x>0){var t=1e3/x;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{F()}),100);const E=function(){let e=Date.now();if(x=e-P,P>0&&x>0){var t=1e3/x;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}I(e),function(e){for(var t in w.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];w.sceneId=t,w.startTime=i.startTime,w.deltaTime=null!=w.prevTime?w.time-w.prevTime:0,i.fire("tick",w,!0)}w.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(F):requestAnimationFrame(E)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}E();class T{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 T))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+_.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,c,h;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,c=0,h=A.length;c<h;c++)l.off(A[c]);delete this._attached[t],delete this._attachments[l.id];const s=e.params.onDetached;s&&(_.isFunction(s)?s(l):s.scope?s.callback.call(s.scope,l):s.callback(l)),e.managingLifecycle&&l.destroy()}if(i){const s={params:e,component:i,subs:[],managingLifecycle:false};s.subs.push(i.once("destroyed",(function(){s.params.component=null,this._attach(s.params)}),this)),a&&s.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=s;const r=e.onAttached;if(r&&(_.isFunction(r)?r(i):r.scope?r.callback.call(r.scope,i):r.callback(i)),n){let e,t,r,o;for(e in n)if(n.hasOwnProperty(e)){if(t=n[e],_.isFunction(t)?(r=t,o=null):(r=t.callback,o=t.scope),!r)continue;s.subs.push(i.on(e,r,o))}}}return a&&this.fire("dirty",this),this.fire(t,i),i}_checkComponent(e,t){if(!t.isComponent){if(!_.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!_.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var i=0,s=e.length;i<s;i++)if(e[i]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r<o;r++)i.off(s[r]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(i=this._ownedComponents[e],i.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const D=h.vec3(),S=h.vec3(),R=h.mat4();class U{constructor(){this.normal=h.vec3(),this.offset=0,this.testVertex=h.vec3()}set(e,t,i,s){const r=1/Math.sqrt(e*e+t*t+i*i);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=i*r,this.offset=s*r,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class L{constructor(){this.planes=[new U,new U,new U,new U,new U,new U]}}function k(e,t,i){const s=h.mulMat4(i,t,R),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],c=s[6],u=s[7],d=s[8],p=s[9],f=s[10],m=s[11],g=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,m-d,b-g),e.planes[1].set(a+r,u+l,m+d,b+g),e.planes[2].set(a-o,u-A,m-p,b-_),e.planes[3].set(a+o,u+A,m+p,b+_),e.planes[4].set(a-n,u-c,m-f,b-v),e.planes[5].set(a+n,u+c,m+f,b+v)}function O(e,t){let i=L.INSIDE;const s=D,r=S;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return L.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=L.INTERSECT)}return i}L.INSIDE=0,L.INTERSECT=1,L.OUTSIDE=2;class N extends T{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=h.vec2(),this._canvasMarqueeCorner2=h.vec2(),this._canvasMarquee=h.AABB2(),this._marqueeFrustum=new L,this._marqueeFrustumProjMat=h.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=L.INTERSECT)=>{if(s===L.INTERSECT&&(s=O(this._marqueeFrustum,i.aabb)),s!==L.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i<s;i++){const s=t[i];if(!s.visible)continue;const r=s.aabb;if(this._pickMode===N.PICK_MODE_INSIDE){O(this._marqueeFrustum,r)===L.INSIDE&&e.push(s.id)}else{O(this._marqueeFrustum,r)!==L.OUTSIDE&&e.push(s.id)}}}i.left&&t(i.left,s),i.right&&t(i.right,s)}};return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,c=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);h.frustumMat4(l,A,c*a,u*a,d,1e4,this._marqueeFrustumProjMat),k(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class V{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class Q{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=H(e,i);return s?t?G(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=H(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=G(r,[t]),i&&(r=G(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function H(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e<t;e++){s=s[i[e]]}return s}function G(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}class j extends T{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=h.subVec3(o,r,[]);return h.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=h.lenVec3(h.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class z extends j{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=h.vec3();return A[0]=h.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=h.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=h.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const W=h.vec3();const X=h.vec3(),K=h.vec3(),Z=h.vec3(),J=h.vec3(),Y=h.vec3();class q extends T{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=h.vec3(),this._eye1=h.vec3(),this._up1=h.vec3(),this._look2=h.vec3(),this._eye2=h.vec3(),this._up2=h.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const c=e.poi;if(o){if(o[3]<o[0]||o[4]<o[1]||o[5]<o[2])return;if(o[3]===o[0]&&o[4]===o[1]&&o[5]===o[2])return;o=o.slice();const t=h.getAABB3Center(o);this._look2=c||t;const i=h.subVec3(this._eye1,this._look1,X),s=h.normalizeVec3(i),r=c?h.getAABB3DiagPoint(o,c):h.getAABB3Diag(o),n=e.fitFOV||this._fitFOV,a=Math.abs(r/Math.tan(n*h.DEGTORAD));this._orthoScale2=1.1*r,this._eye2[0]=this._look2[0]+s[0]*a,this._eye2[1]=this._look2[1]+s[1]*a,this._eye2[2]=this._look2[2]+s[2]*a,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(n||a||l)&&(this._flyingEyeLookUp=!!n&&!!a&&!!l,this._flyingEye=!!n&&!a,this._flyingLook=!!a&&!n,n&&(this._eye2[0]=n[0],this._eye2[1]=n[1],this._eye2[2]=n[2]),a&&(this._look2[0]=a[0],this._look2[1]=a[1],this._look2[2]=a[2]),l&&(this._up2[0]=l[0],this._up2[1]=l[1],this._up2[2]=l[2]));r?("ortho"===e.projection&&"ortho"!==s.projection&&(this._projection2="ortho",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.ortho.matrix.slice(),s.projection="customProjection"),"perspective"===e.projection&&"perspective"!==s.projection&&(this._projection2="perspective",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.perspective.matrix.slice(),s.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(Number.isFinite(e.duration)?1e3*e.duration:this._duration),this._flying=!0,M.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var i,s,r,o,n;if(e.aabb)i=e.aabb;else if(6===e.length)i=e;else if(e.eye||e.look||e.up)r=e.eye,o=e.look,n=e.up;else{let t=e;if((_.isNumeric(t)||_.isString(t))&&(s=t,t=this.scene.components[s],!t))return void this.error("Component not found: "+_.inQuotes(s));i=t.aabb||this.scene.aabb}const a=e.poi;if(i){if(i[3]<=i[0]||i[4]<=i[1]||i[5]<=i[2])return;var l=a?h.getAABB3DiagPoint(i,a):h.getAABB3Diag(i);let s;o=a||h.getAABB3Center(i,o),this._trail?h.subVec3(t.look,o,Y):h.subVec3(t.eye,t.look,Y),h.normalizeVec3(Y);s=(void 0!==e.fit?e.fit:this._fit)?Math.abs(l/Math.tan((e.fitFOV||this._fitFOV)*h.DEGTORAD)):h.lenVec3(h.subVec3(t.eye,t.look,X)),h.mulVec3Scalar(Y,s),t.eye=h.addVec3(o,Y,X),t.look=o,this.scene.camera.ortho.scale=1.1*l}else(r||o||n)&&(r&&(t.eye=r),o&&(t.look=o),n&&(t.up=n));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const i=this.easing?q._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(h.subVec3(s.eye,s.look,Y),s.eye=h.lerpVec3(i,0,1,this._eye1,this._eye2,Z),s.look=h.subVec3(Z,Y,K)):this._flyingLook&&(s.look=h.lerpVec3(i,0,1,this._look1,this._look2,K),s.up=h.lerpVec3(i,0,1,this._up1,this._up2,J)):this._flyingEyeLookUp&&(s.eye=h.lerpVec3(i,0,1,this._eye1,this._eye2,Z),s.look=h.lerpVec3(i,0,1,this._look1,this._look2,K),s.up=h.lerpVec3(i,0,1,this._up1,this._up2,J)),this._projection2){const t="ortho"===this._projection2?q._easeOutExpo(e,0,1,1):q._easeInCubic(e,0,1,1);s.customProjection.matrix=h.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=Number.isFinite(e)?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class $ extends T{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new q(this),this._t=0,this.state=$.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case $.SCRUBBING:return;case $.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=$.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case $.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=$.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=$.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=$.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=$.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=$.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=$.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=$.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}$.STOPPED=0,$.SCRUBBING=1,$.PLAYING=2,$.PLAYING_TO=3;class ee extends T{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}const te=new e({});class ie{constructor(e){this.id=te.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){te.removeItem(this.id)}}class se{constructor(e,t,i,s,r,o,n,a,l){switch(this._gl=e,this.type=t,this.allocated=!1,this.ConstructorType=i.constructor,i.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=o,this.length=0,this.dataLength=s,this.numItems=0,this.itemSize=r,this.normalized=!!n,this.stride=a||0,this.offset=l||0,this._allocate(i)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}getData(e=0,t=this.numItems-e){if(!this.allocated)return[];const i=new this.ConstructorType(t*this.itemSize);return this._gl.bindBuffer(this.type,this._handle),this._gl.getBufferSubData(this.type,e*this.itemByteSize*this.itemSize,i,0,t*this.itemSize),i}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}var re=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=h.vec3(),c=h.vec3(),u=h.vec3(),d=h.vec3(),p=h.vec3(),f=h.vec3(),m=h.vec3();return function(g,_,v,b){!function(r,o){const n={};let a,l,A,c;const h=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;u<d;u+=3)a=r[u],l=r[u+1],A=r[u+2],c=Math.round(a*h)+"_"+Math.round(l*h)+"_"+Math.round(A*h),void 0===n[c]&&(n[c]=p/3,e[p++]=a,e[p++]=l,e[p++]=A),t[u/3]=n[c];for(u=0,d=o.length;u<d;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,_),function(t,i){o=0;for(let g=0,_=t;g<_;g+=3){const t=3*s[g],_=3*s[g+1],v=3*s[g+2];i?(n[0]=e[t],n[1]=e[t+1],n[2]=e[t+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(n,i,A),h.decompressPosition(a,i,c),h.decompressPosition(l,i,u)):(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],u[0]=e[v],u[1]=e[v+1],u[2]=e[v+2]),h.subVec3(u,c,d),h.subVec3(A,c,p),h.cross3Vec3(d,p,f),h.normalizeVec3(f,m);const b=r[o]||(r[o]={normal:h.vec3()});b.normal[0]=m[0],b.normal[1]=m[1],b.normal[2]=m[2],o++}}(_.length,v);const y=[],w=Math.cos(h.DEGTORAD*b),B={};let x,P,C,M,F,E,I,T,D,S,R,U=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)x=s[e+i],P=s[e+(i+1)%3],C=Math.min(x,P),M=Math.max(x,P),F=C+","+M,void 0===B[F]?B[F]={index1:C,index2:M,face1:t,face2:void 0}:B[F].face2=t}for(F in B)E=B[F],void 0!==E.face2&&(I=r[E.face1].normal,T=r[E.face2].normal,D=h.dotVec3(I,T),D>w)||(S=i[E.index1],R=i[E.index2],(!U&&S>65535||R>65535)&&(U=!0),y.push(S),y.push(R));return U?new Uint32Array(y):new Uint16Array(y)}}();const oe=function(){const e=h.mat4(),t=h.mat4();return function(i,s){s=s||h.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,c=65535;return h.identityMat4(e),h.translationMat4v(i,e),h.identityMat4(t),h.scalingMat4v([a/c,l/c,A/c],t),h.mulMat4(e,t,s),s}}();var ne=function(){const e=h.mat4(),t=h.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a<i.length;a+=3)o[a+0]=Math.max(0,Math.min(65535,Math.floor((i[a+0]-s[0])*n[0]))),o[a+1]=Math.max(0,Math.min(65535,Math.floor((i[a+1]-s[1])*n[1]))),o[a+2]=Math.max(0,Math.min(65535,Math.floor((i[a+2]-s[2])*n[2])));h.identityMat4(e),h.translationMat4v(s,e),h.identityMat4(t),h.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t);return{quantized:o,decodeMatrix:h.mulMat4(e,t,h.identityMat4())}}}();var ae=function(){const e=h.mat3(),t=h.mat3();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);let a;for(a=0;a<i.length;a+=2)o[a+0]=Math.max(0,Math.min(65535,Math.floor((i[a+0]-s[0])*n[0]))),o[a+1]=Math.max(0,Math.min(65535,Math.floor((i[a+1]-s[1])*n[1])));h.identityMat3(e),h.translationMat3v(s,e),h.identityMat3(t),h.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t);return{quantized:o,decodeMatrix:h.mulMat3(e,t,h.identityMat3())}}}();function le(e,t,i,s){let r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),o=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){let e=(1-Math.abs(o))*(r>=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function Ae(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function ce(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const he={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=3)for(r=0;r<3;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},createPositionsDecodeMatrix:oe,compressPositions:ne,compressPosition:function(e,t,i){const s=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);i[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*s[0]))),i[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*s[1]))),i[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*s[2])))},decompressPositions:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t,i=e){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){const t=new Float32Array(2),i=new Float32Array(2);let s,r;for(s=0;s<2;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=2)for(r=0;r<2;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},compressUVs:ae,decompressUVs:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let i,s,r,o,n;for(let a=0;a<e.length;a+=3)r=i=le(e,a,"floor","floor"),s=Ae(i),o=n=ce(e,a,s),i=le(e,a,"ceil","floor"),s=Ae(i),o=ce(e,a,s),o>n&&(r=i,n=o),i=le(e,a,"floor","ceil"),s=Ae(i),o=ce(e,a,s),o>n&&(r=i,n=o),i=le(e,a,"ceil","ceil"),s=Ae(i),o=ce(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const n=1-Math.abs(r)-Math.abs(o);n<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},ue=p.memory,de=h.AABB3();class pe extends ee{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new ie({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=he.getPositionsBounds(t.positions),s=he.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=he.getUVBounds(t.uv),s=he.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=he.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),ue.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),ue.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new se(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),ue.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new se(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),ue.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new se(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),ue.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new se(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),ue.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=re(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),ue.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=h.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new se(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new se(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),ue.positions+=this._pickTrianglePositionsBuf.numItems,ue.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),he.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=he.getPositionsBounds(e),s=he.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),he.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),he.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=h.AABB3()),h.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=h.OBB3()),h.positions3ToAABB3(this._state.positions,de,this._state.positionsDecodeMatrix),h.AABB3ToOBB3(de,this._obb),this._obbDirty=!1),this._obb}_getMetrics(){if(!("_metrics"in this))switch(this._state.primitiveName){case"solid":case"surface":case"triangles":{const e=this._state.indices,t=this._state.positions,i=(i,s)=>{const r=3*e[i];for(let e=0;e<3;++e)s[e]=t[r+e];return s},s=[h.vec3(),h.vec3(),h.vec3(),h.vec3()];let r=0;const o=h.vec3([0,0,0]);for(let t=0;t<e.length;t+=3){const e=i(t,s[0]),n=i(t+1,s[1]),a=i(t+2,s[2]);h.addVec3(e,n,s[3]),h.addVec3(a,s[3],s[3]);const l=h.lenVec3(h.cross3Vec3(h.subVec3(n,e,s[1]),h.subVec3(a,e,s[2]),s[0]))/2;r+=l,h.mulVec3Scalar(s[3],l,s[3]),h.addVec3(o,s[3],o)}this._metrics={surfaceArea:r,centroid:h.mulVec3Scalar(o,1/r/3,o)};break}default:this._metrics={surfaceArea:0}}return this._metrics}get surfaceArea(){return this._getMetrics().surfaceArea}get centroid(){return this._getMetrics().centroid}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),ue.meshes--}}const fe=p.memory,me=h.AABB3();class ge extends ee{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new ie({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=h.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=he.getPositionsBounds(t.positions),o=he.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new se(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),fe.positions+=i.positionsBuf.numItems,h.positions3ToAABB3(t.positions,this._aabb),h.positions3ToAABB3(r,me,i.positionsDecodeMatrix),h.AABB3ToOBB3(me,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new se(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),fe.colors+=i.colorsBuf.numItems}if(t.uv){const e=he.getUVBounds(t.uv),r=he.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new se(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),fe.uvs+=i.uvBuf.numItems}if(t.normals){const e=he.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new se(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),fe.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),fe.indices+=i.indicesBuf.numItems;const o=re(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),fe.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(),fe.meshes--}}var _e={};function ve(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,c=-s+a,h=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[h,u,d,l,u,d,l,A,d,h,A,d,h,u,d,h,A,d,h,A,c,h,u,c,h,u,d,h,u,c,l,u,c,l,u,d,l,u,d,l,u,c,l,A,c,l,A,d,l,A,c,h,A,c,h,A,d,l,A,d,h,A,c,l,A,c,l,u,c,h,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}function be(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,c=-s+a,h=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,c,l,A,d,l,u,c,l,u,d,h,A,c,h,A,d,h,u,c,h,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function ye(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,c=a?a[2]:0,h=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,m=[],g=[],v=[],b=[];let y,w,B,x,P,C,M,F,E,I,T;const D=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=h-y*u,w=0;w<=r;w++)B=Math.sin(w*d),x=Math.cos(w*d),g.push(P*B),g.push(D),g.push(P*x),v.push(w*p),v.push(1*y/o),m.push(P*B+l),m.push(C+A),m.push(P*x+c);for(y=0;y<o;y++)for(w=0;w<=r;w++)M=y*(r+1)+w,F=M+r,b.push(M),b.push(F),b.push(F+1),b.push(M),b.push(F+1),b.push(M+1);if(!n&&t>0){for(E=m.length/3,g.push(0),g.push(1),g.push(0),v.push(.5),v.push(.5),m.push(0+l),m.push(h+A),m.push(0+c),w=0;w<=r;w++)B=Math.sin(w*d),x=Math.cos(w*d),I=.5*Math.sin(w*d)+.5,T=.5*Math.cos(w*d)+.5,g.push(t*B),g.push(1),g.push(t*x),v.push(I),v.push(T),m.push(t*B+l),m.push(h+A),m.push(t*x+c);for(w=0;w<r;w++)a=E,M=E+1+w,b.push(M),b.push(M+1),b.push(a)}if(!n&&i>0){for(E=m.length/3,g.push(0),g.push(-1),g.push(0),v.push(.5),v.push(.5),m.push(0+l),m.push(0-h+A),m.push(0+c),w=0;w<=r;w++)B=Math.sin(w*d),x=Math.cos(w*d),I=.5*Math.sin(w*d)+.5,T=.5*Math.cos(w*d)+.5,g.push(i*B),g.push(-1),g.push(i*x),v.push(I),v.push(T),m.push(i*B+l),m.push(0-h+A),m.push(i*x+c);for(w=0;w<r;w++)a=E,M=E+1+w,b.push(a),b.push(M+1),b.push(M)}return _.apply(e,{positions:m,normals:g,uv:v,indices:b})}function we(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Be(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,c=i/2,h=Math.floor(s)||1,u=Math.floor(r)||1,d=h+1,p=u+1,f=t/h,m=i/u,g=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,w,B,x,P,C,M,F=0,E=0;for(y=0;y<p;y++){const e=y*m-c;for(w=0;w<d;w++)B=w*f-A,g[F]=B+n,g[F+1]=a,g[F+2]=-e+l,v[F+1]=1,b[E]=w/h,b[E+1]=(u-y)/u,F+=3,E+=2}F=0;const I=new(g.length/3>65535?Uint32Array:Uint16Array)(h*u*6);for(y=0;y<u;y++)for(w=0;w<h;w++)x=w+d*y,P=w+d*(y+1),C=w+1+d*(y+1),M=w+1+d*y,I[F]=M,I[F+1]=P,I[F+2]=x,I[F+3]=M,I[F+4]=C,I[F+5]=P,F+=6;return _.apply(e,{positions:g,normals:v,uv:b,indices:I})}function xe(e={}){const t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0;let o=e.radius||1;o<0&&(console.error("negative radius not allowed - will invert"),o*=-1);let n=e.heightSegments||18;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n=Math.floor(t*n),n<18&&(n=18);let a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),a=Math.floor(t*a),a<18&&(a=18);const l=[],A=[],c=[],h=[];let u,d,p,f,m,g,v,b,y,w,B,x,P,C,M;for(u=0;u<=n;u++)for(p=u*Math.PI/n,f=Math.sin(p),m=Math.cos(p),d=0;d<=a;d++)g=2*d*Math.PI/a,v=Math.sin(g),b=Math.cos(g),y=b*f,w=m,B=v*f,x=1-d/a,P=u/n,A.push(y),A.push(w),A.push(B),c.push(x),c.push(P),l.push(i+o*y),l.push(s+o*w),l.push(r+o*B);for(u=0;u<n;u++)for(d=0;d<a;d++)C=u*(a+1)+d,M=C+a+1,h.push(C+1),h.push(M+1),h.push(M),h.push(C+1),h.push(M),h.push(C);return _.apply(e,{positions:l,normals:A,uv:c,indices:h})}function Pe(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);let s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);let r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);let o=e.arc||2*Math.PI;o<0&&(console.warn("negative arc not allowed - will invert"),o*=-1),o>360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,c=[],u=[],d=[],p=[];let f,m,g,v,b,y,w,B,x,P,C,M;for(B=0;B<=r;B++)for(w=0;w<=s;w++)f=w/s*o,m=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),g=(t+i*Math.cos(m))*Math.cos(f),v=(t+i*Math.cos(m))*Math.sin(f),b=i*Math.sin(m),c.push(g+a),c.push(v+l),c.push(b+A),d.push(1-w/s),d.push(B/r),y=h.normalizeVec3(h.subVec3([g,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(B=1;B<=r;B++)for(w=1;w<=s;w++)x=(s+1)*B+w-1,P=(s+1)*(B-1)+w-1,C=(s+1)*(B-1)+w,M=(s+1)*B+w,p.push(x),p.push(P),p.push(C),p.push(C),p.push(M),p.push(x);return _.apply(e,{positions:c,normals:u,uv:d,indices:p})}_e.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},_e.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(_e.parse._buffToStr(e));window.location.href=i},_e.clone=function(e){return JSON.parse(JSON.stringify(e))},_e.bin={},_e.bin.f=new Float32Array(1),_e.bin.fb=new Uint8Array(_e.bin.f.buffer),_e.bin.rf=function(e,t){for(var i=_e.bin.f,s=_e.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},_e.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},_e.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},_e.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},_e.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},_e.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},_e.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},_e.parse={},_e.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;s<t.length;s++)i=i.concat(String.fromCharCode(t[s]));return i},_e.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),i=new Uint8Array(t),s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return t},_e.parse._readLine=function(e,t){for(var i="";10!=e[t];)i+=String.fromCharCode(e[t++]);return i},_e.parse.fromJSON=function(e){return JSON.parse(_e.parse._buffToStr(e))},_e.parse.toJSON=function(e){var t=JSON.stringify(e);return _e.parse._strToBuff(t)},_e.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},i={from:0,to:0},s=0,r=new Uint8Array(e);s<r.length;){var o=_e.parse._readLine(r,s);s+=o.length+1;var n=(o=(o=o.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==n[0]&&(i.to=t.i_verts.length,null==t.groups[n[1]]&&(t.groups[n[1]]={from:t.i_verts.length,to:0}),i=t.groups[n[1]]),"v"==n[0]){var a=parseFloat(n[1]),l=parseFloat(n[2]),A=parseFloat(n[3]);t.c_verts.push(a,l,A)}if("vt"==n[0]){a=parseFloat(n[1]),l=1-parseFloat(n[2]);t.c_uvt.push(a,l)}if("vn"==n[0]){a=parseFloat(n[1]),l=parseFloat(n[2]),A=parseFloat(n[3]);t.c_norms.push(a,l,A)}if("f"==n[0]){var c=n[1].split("/"),h=n[2].split("/"),u=n[3].split("/"),d=parseInt(c[0])-1,p=parseInt(h[0])-1,f=parseInt(u[0])-1,m=parseInt(c[1])-1,g=parseInt(h[1])-1,_=parseInt(u[1])-1,v=parseInt(c[2])-1,b=parseInt(h[2])-1,y=parseInt(u[2])-1,w=t.c_verts.length/3,B=t.c_uvt.length/2,x=t.c_norms.length/3;if(d<0&&(d=w+d+1),p<0&&(p=w+p+1),f<0&&(f=w+f+1),m<0&&(m=B+m+1),g<0&&(g=B+g+1),_<0&&(_=B+_+1),v<0&&(v=x+v+1),b<0&&(b=x+b+1),y<0&&(y=x+y+1),t.i_verts.push(d,p,f),t.i_uvt.push(m,g,_),t.i_norms.push(v,b,y),5==n.length){var P=n[4].split("/"),C=parseInt(P[0])-1,M=parseInt(P[1])-1,F=parseInt(P[2])-1;C<0&&(C=w+C+1),M<0&&(M=B+M+1),F<0&&(F=x+F+1),t.i_verts.push(d,f,C),t.i_uvt.push(m,_,M),t.i_norms.push(v,y,F)}}}return i.to=t.i_verts.length,t},_e.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},i={};i.ident=_e.bin.ril(e,0),i.version=_e.bin.ril(e,4),i.skinwidth=_e.bin.ril(e,8),i.skinheight=_e.bin.ril(e,12),i.framesize=_e.bin.ril(e,16),i.num_skins=_e.bin.ril(e,20),i.num_vertices=_e.bin.ril(e,24),i.num_st=_e.bin.ril(e,28),i.num_tris=_e.bin.ril(e,32),i.num_glcmds=_e.bin.ril(e,36),i.num_frames=_e.bin.ril(e,40),i.offset_skins=_e.bin.ril(e,44),i.offset_st=_e.bin.ril(e,48),i.offset_tris=_e.bin.ril(e,52),i.offset_frames=_e.bin.ril(e,56),i.offset_glcmds=_e.bin.ril(e,60),i.offset_end=_e.bin.ril(e,64);var s=i.offset_st;t.c_uvt=[];for(var r=0;r<i.num_st;r++){var o=_e.bin.rsl(e,s)/i.skinwidth,n=_e.bin.rsl(e,s+2)/i.skinheight;t.c_uvt.push(o,n),s+=4}s=i.offset_tris;var a=[],l=[];t.i_verts=a,t.i_uvt=l;for(r=0;r<i.num_tris;r++)a.push(_e.bin.rsl(e,s),_e.bin.rsl(e,s+2),_e.bin.rsl(e,s+4)),l.push(_e.bin.rsl(e,s+6),_e.bin.rsl(e,s+8),_e.bin.rsl(e,s+10)),s+=12;s=i.offset_skins;t.skins=[];for(r=0;r<i.num_skins;r++)t.skins.push(_e.bin.rASCII0(e,s)),s+=64;s=i.offset_frames;t.frames=[];var A=_e.parse.fromMD2._normals;for(r=0;r<i.num_frames;r++){var c={},h=_e.bin.rf(e,s),u=_e.bin.rf(e,s+4),d=_e.bin.rf(e,s+8);s+=12;var p=_e.bin.rf(e,s),f=_e.bin.rf(e,s+4),m=_e.bin.rf(e,s+8);s+=12,c.name=_e.bin.rASCII0(e,s),s+=16,c.verts=[],c.norms=[];for(var g=0;g<i.num_vertices;g++)c.verts.push(e[s]*h+p,e[s+1]*u+f,e[s+2]*d+m),c.norms.push(A[3*e[s+3]],A[3*e[s+3]+1],A[3*e[s+3]+2]),s+=4;t.frames.push(c)}return t},_e.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],_e.parse.fromCollada=function(e){var t=_e.parse._buffToStr(e),i=(new DOMParser).parseFromString(t,"text/xml"),s={},r=(i=i.childNodes[0]).getElementsByTagName("asset")[0],o=i.getElementsByTagName("library_geometries")[0],n=i.getElementsByTagName("library_images")[0],a=i.getElementsByTagName("library_materials")[0],l=i.getElementsByTagName("library_effects")[0];return r&&(s.asset=_e.parse.fromCollada._asset(r)),o&&(s.geometries=_e.parse.fromCollada._libGeometries(o)),n&&(s.images=_e.parse.fromCollada._libImages(n)),a&&(s.materials=_e.parse.fromCollada._libMaterials(a)),l&&(s.effects=_e.parse.fromCollada._libEffects(l)),s},_e.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},_e.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],i=0;i<e.length;i++){var s=e[i],r=_e.parse.fromCollada._getMesh(s.getElementsByTagName("mesh")[0]);t.push(r)}return t},_e.parse.fromCollada._getMesh=function(e){for(var t={},i=e.getElementsByTagName("source"),s=t.sources={},r=0;r<i.length;r++){for(var o=i[r].getElementsByTagName("float_array")[0].textContent.split(" "),n=o.length-(""==o[o.length-1]?1:0),a=new Array(n),l=0;l<n;l++)a[l]=parseFloat(o[l]);s[i[r].getAttribute("id")]=a}t.triangles=[];var A=e.getElementsByTagName("triangles");if(null==A)return t;for(r=0;r<A.length;r++){var c={},h=A[r];c.material=h.getAttribute("material");var u=h.getElementsByTagName("input"),d=[];for(l=0;l<u.length;l++){var p=u[l];a=[];d[parseInt(p.getAttribute("offset"))]=a;var f=p.getAttribute("semantic");c["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):p.getAttribute("source").substring(1),c["i_"+f]=a,s[c["s_"+f]]}var m=h.getElementsByTagName("p")[0].textContent.split(" "),g=3*Math.floor(m.length/3);for(l=0;l<g;l++)d[l%u.length].push(parseInt(m[l]));t.triangles.push(c)}return t},_e.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("id")]=e[i].getElementsByTagName("init_from")[0].textContent;return t},_e.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("name")]=e[i].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},_e.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},i=0;i<e.length;i++){for(var s={},r=e[i].getElementsByTagName("newparam"),o=0;o<r.length;o++){var n=r[o].getElementsByTagName("surface")[0];n&&(s.surface=n.getElementsByTagName("init_from")[0].textContent)}t[e[i].getAttribute("id")]=s}return t},_e.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=_e.bin.rsl(e,0))return null;for(var i=_e.bin.ril(e,2),s=6;s<i;){var r=_e.bin.rsl(e,s),o=_e.bin.ril(e,s+2);15677==r&&(t.edit=_e.parse.from3DS._edit3ds(e,s,o)),45056==r&&(t.keyf=_e.parse.from3DS._keyf3ds(e,s,o)),s+=o}return t},_e.parse.from3DS._edit3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);16384==o&&(null==s.objects&&(s.objects=[]),s.objects.push(_e.parse.from3DS._edit_object(e,r,n))),r+=n}return s},_e.parse.from3DS._keyf3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);45058==o&&(null==s.desc&&(s.desc=[]),s.desc.push(_e.parse.from3DS._keyf_objdes(e,r,n))),r+=n}return s},_e.parse.from3DS._keyf_objdes=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);45072==o&&(s.hierarchy=_e.parse.from3DS._keyf_objhierarch(e,r,n)),45073==o&&(s.dummy_name=_e.bin.rASCII0(e,r+6)),r+=n}return s},_e.parse.from3DS._keyf_objhierarch=function(e,t,i){var s={},r=t+6;return s.name=_e.bin.rASCII0(e,r),r+=s.name.length+1,s.hierarchy=_e.bin.rsl(e,r+4),s},_e.parse.from3DS._edit_object=function(e,t,i){var s={},r=t+6;for(s.name=_e.bin.rASCII0(e,r),r+=s.name.length+1;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);16640==o&&(s.mesh=_e.parse.from3DS._obj_trimesh(e,r,n)),r+=n}return s},_e.parse.from3DS._obj_trimesh=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);16656==o&&(s.vertices=_e.parse.from3DS._tri_vertexl(e,r,n)),16672==o&&(s.indices=_e.parse.from3DS._tri_facel1(e,r,n)),16704==o&&(s.uvt=_e.parse.from3DS._tri_mappingcoors(e,r,n)),16736==o&&(s.local=_e.parse.from3DS._tri_local(e,r,n)),r+=n}return s},_e.parse.from3DS._tri_vertexl=function(e,t,i){var s=[],r=t+6,o=_e.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)s.push(_e.bin.rf(e,r)),s.push(_e.bin.rf(e,r+4)),s.push(_e.bin.rf(e,r+8)),r+=12;return s},_e.parse.from3DS._tri_facel1=function(e,t,i){var s=[],r=t+6,o=_e.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)s.push(_e.bin.rsl(e,r)),s.push(_e.bin.rsl(e,r+2)),s.push(_e.bin.rsl(e,r+4)),r+=8;return s},_e.parse.from3DS._tri_mappingcoors=function(e,t,i){var s=[],r=t+6,o=_e.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)s.push(_e.bin.rf(e,r)),s.push(1-_e.bin.rf(e,r+4)),r+=8;return s},_e.parse.from3DS._tri_local=function(e,t,i){var s={},r=t+6;return s.X=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s.Y=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s.Z=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s.C=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s},_e.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},i={};return i.id=_e.bin.ril(e,0),i.verS=_e.bin.ril(e,4),i.texS=_e.bin.ril(e,8),i.indS=_e.bin.ril(e,12),i.verO=_e.bin.ril(e,16),i.verL=_e.bin.ril(e,20),i.texO=_e.bin.ril(e,24),i.texL=_e.bin.ril(e,28),i.indO=_e.bin.ril(e,32),i.indL=_e.bin.ril(e,36),0!=i.verO&&(t.vertices=_e.parse.fromBIV._readFloats(e,i.verO,i.verL)),0!=i.texO&&(t.uvt=_e.parse.fromBIV._readFloats(e,i.texO,i.texL)),0!=i.indO&&(t.indices=_e.parse.fromBIV._readInts(e,i.indO,i.indL,i.indS)),t},_e.parse.toBIV=function(e){for(var t=0,i=0;i<e.indices.length;i++)t=Math.max(t,e.indices[i]);var s=32;t<=65535&&(s=16);var r=40;e.vertices&&(r+=4*e.vertices.length),e.uvt&&(r+=4*e.uvt.length),e.indices&&(r+=e.indices.length*s/8);var o=new Uint8Array(r);_e.bin.wil(o,0,1769365870),_e.bin.wil(o,4,32),_e.bin.wil(o,8,32),_e.bin.wil(o,12,s);var n=40;return e.vertices&&(_e.bin.wil(o,16,n),_e.bin.wil(o,20,4*e.vertices.length),_e.parse.fromBIV._writeFloats(o,n,e.vertices),n+=4*e.vertices.length),e.uvt&&(_e.bin.wil(o,24,n),_e.bin.wil(o,28,4*e.uvt.length),_e.parse.fromBIV._writeFloats(o,n,e.uvt),n+=4*e.uvt.length),e.indices&&(_e.bin.wil(o,32,n),_e.bin.wil(o,36,4*e.indices.length),_e.parse.fromBIV._writeInts(o,n,e.indices,s)),o.buffer},_e.parse.fromBIV._readFloats=function(e,t,i){for(var s=[],r=0;r<i/4;r++)s.push(_e.bin.rf(e,t+4*r));return s},_e.parse.fromBIV._writeFloats=function(e,t,i){for(var s=0;s<i.length;s++)_e.bin.wf(e,t+4*s,i[s])},_e.parse.fromBIV._readInts=function(e,t,i,s){for(var r=[],o=0;o<i/4;o++)16==s&&r.push(_e.bin.rsl(e,t+2*o)),32==s&&r.push(_e.bin.ril(e,t+4*o));return r},_e.parse.fromBIV._writeInts=function(e,t,i,s){for(var r=0;r<i.length;r++)16==s&&_e.bin.wsl(e,t+2*r,i[r]),32==s&&_e.bin.wil(e,t+4*r,i[r])},_e.gen={},_e.gen.Plane=function(e,t,i,s){i||(i=1),s||(s=1);for(var r={verts:[],inds:[],uvt:[]},o=e+1,n=t+1,a=0;a<n;a++)for(var l=0;l<o;l++){var A=l*(2/e)-1,c=a*(2/t)-1;r.verts.push(A,c,0),r.uvt.push(i*l/e,s*a/t),a<t&&l<e&&r.inds.push(a*o+l,a*o+l+1,(a+1)*o+l,a*o+l+1,(a+1)*o+l,(a+1)*o+l+1)}return r},_e.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},_e.gen.Sphere=function(e,t){for(var i={verts:[],inds:[],uvt:[]},s=e+1,r=t+1,o=0;o<r;o++)for(var n=0;n<s;n++){var a=-Math.PI/2+o*Math.PI/t,l=2*n*Math.PI/e,A=Math.cos(a)*Math.cos(l),c=Math.sin(a),h=Math.cos(a)*Math.sin(l);i.verts.push(A,c,h),i.uvt.push(n/e,o/t),o<t&&n<e&&i.inds.push(s*o+n,s*o+n+1,s*(o+1)+n,s*o+n+1,s*(o+1)+n,s*(o+1)+n+1)}return i},_e.mat={},_e.mat.scale=function(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]},_e.mat.translate=function(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]},_e.mat.rotateDeg=function(e,t,i){var s=Math.PI/180;return _e.mat.rotate(e*s,t*s,i*s)},_e.mat.rotate=function(e,t,i){var s=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],r=e,o=t,n=i,a=Math.cos(r),l=Math.cos(o),A=Math.cos(n),c=Math.sin(r),h=Math.sin(o),u=Math.sin(n);return s[0]=l*A,s[1]=-l*u,s[2]=h,s[4]=a*u+c*h*A,s[5]=a*A-c*h*u,s[6]=-c*l,s[8]=c*u-a*h*A,s[9]=c*A+a*h*u,s[10]=a*l,s},_e.edit={},_e.edit.interpolate=function(e,t,i,s){for(var r=0;r<e.length;r++)i[r]=e[r]+s*(t[r]-e[r])},_e.edit.transform=function(e,t){for(var i=0;i<e.length;i+=3){var s=e[i],r=e[i+1],o=e[i+2];e[i+0]=t[0]*s+t[4]*r+t[8]*o+t[12],e[i+1]=t[1]*s+t[5]*r+t[9]*o+t[13],e[i+2]=t[2]*s+t[6]*r+t[10]*o+t[14]}},_e.edit.unwrap=function(e,t,i){for(var s=new Array(Math.floor(e.length/3)*i),r=0;r<e.length;r++)for(var o=0;o<i;o++)s[r*i+o]=t[e[r]*i+o];return s},_e.edit.remap=function(e,t,i,s){for(var r=new Array(i.length),o=0;o<e.length;o++)for(var n=0;n<s;n++)r[t[o]*s+n]=i[e[o]*s+n];return r},_e.utils={},_e.utils.getAABB=function(e){var t,i,s,r,o,n;r=o=n=-(t=i=s=999999999);for(var a=0;a<e.length;a+=3){var l=e[a+0],A=e[a+1],c=e[a+2];l<t&&(t=l),l>r&&(r=l),A<i&&(i=A),A>o&&(o=A),c<s&&(s=c),A>n&&(n=c)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};const Ce={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function Me(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,c,h,u,d,p,f,m,g,v=(l||"").split("\n"),b=0,y=0,w=.04,B=0;B<v.length;B++){A=0,h=(c=v[B]).length;for(var x=0;x<h;x++)if(u=Ce[c.charAt(x)]){d=1,p=-1,f=-1,m=u.points.length;for(var P=0;P<m;P++)-1!==(g=u.points[P])[0]||-1!==g[1]?(n.push(A+g[0]*o*w+i),n.push(y+g[1]*o*w+s),n.push(0+r),-1===p?p=b:(-1===f||(p=f),f=b),b++,d?d=!1:(a.push(p),a.push(f))):d=1;A+=u.width*w*o}y-=35*w*o}return _.apply(e,{primitive:"lines",positions:n,indices:a})}function Fe(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e<t-1;e++)i.push(e),i.push(e+1);return _.apply(e,{primitive:"lines",positions:e.points,indices:i})}function Ee(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],o=e.startPoint[2],n=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],A=Math.sqrt((n-s)**2+(a-r)**2+(l-o)**2),c=[(n-s)/A,(a-r)/A,(l-o)/A];if(e.pattern){let h=e.pattern.length,u=!1,d=0,p=0,f=0,m=[s,r,o],g=e.pattern[p];for(i.push(m[0],m[1],m[2]);g<=A-d;){let s=[c[0]*g,c[1]*g,c[2]*g],r=[m[0]+s[0],m[1]+s[1],m[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(f),t.push(f+1)),u=!u,f+=1,m=r,p+=1,p>=h&&(p=0),d+=g,g=e.pattern[p]}e.extendToEnd&&(i.push(n,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,o,n,a,l);return _.apply(e,{primitive:"lines",positions:i,indices:t})}const Ie=h.vec4(4),Te=h.vec4(),De=h.vec4(),Se=h.vec3([1,0,0]),Re=h.vec3([0,1,0]),Ue=h.vec3([0,0,1]),Le=h.vec3(3),ke=h.vec3(3),Oe=h.identityMat4();class Ne extends T{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._offset=h.vec3(),this._localMatrix=h.identityMat4(),this._worldMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let i=0,s=e.length;i<s;i++)this.addChild(e[i],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=h.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,i=this._children.length;t<i;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,i=this._children.length;e<i;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,i=this._children.length;t<i;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,i=e._children.length;t<i;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;h.collapseAABB3(this._aabb);for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e.collidable&&h.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(_.isNumeric(e)||_.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+_.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,i=this._children.length;t<i;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(_.isNumeric(e)||_.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+_.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=h.identityMat4()),this._localMatrix.set(e||Oe),h.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return Ie[0]=e[0],Ie[1]=e[1],Ie[2]=e[2],Ie[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ie,Te),h.mulQuaternions(this.quaternion,Te,De),this.quaternion=De,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ie[0]=e[0],Ie[1]=e[1],Ie[2]=e[2],Ie[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ie,Te),h.mulQuaternions(Te,this.quaternion,Te),this}rotateX(e){return this.rotate(Se,e)}rotateY(e){return this.rotate(Re,e)}rotateZ(e){return this.rotate(Ue,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Le),h.mulVec3Scalar(Le,t,ke),h.addVec3(this.position,ke,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Se,e)}translateY(e){return this.translate(Re,e)}translateZ(e){return this.translate(Ue,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice(0);let t;for(let i=0,s=e.length;i<s;i++)t=e[i],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}const Ve=h.vec3(),Qe=h.vec4(),He=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,h.transformVec4(s,t,i),h.setMat4Translation(s,i,o),o.slice()}}();function Ge(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function je(e,t,i,s=1e3){const r=h.getPositionsCenter(e,Ve),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i<s;i+=3)t[i+0]=e[i+0]-o,t[i+1]=e[i+1]-n,t[i+2]=e[i+2]-a;return l}function ze(e,t,i,s,r){const o=r?(Qe.set(i,0),Qe[3]=1,h.mulMat4v4(r,Qe,Qe)):i,n=h.dotVec3(t,o)+e,a=h.normalizeVec3(t,Ve);return h.mulVec3Scalar(a,-n,s),s}const We=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(A.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&A.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&A.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(A.push("uniform vec3 lightPos"+e+";"),A.push("uniform vec3 lightDir"+e+";")))}l&&(A.push("vec3 octDecode(vec2 oct) {"),A.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),A.push(" if (v.z < 0.0) {"),A.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?A.push("viewLightDir = normalize(lightDir"+e+");"):A.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?A.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):A.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?A.push("viewLightDir = normalize(lightDir"+e+");"):A.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}A.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),A.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}A.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),a&&A.push("vWorldPosition = worldPosition;");"points"===r.primitiveName&&A.push("gl_PointSize = pointSize;");A.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(A.push("vFragDepth = 1.0 + clipPos.w;"),A.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return A.push("gl_Position = clipPos;"),A.push("}"),A}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState;e._material._state;const s=e._geometry._state,r=i.getNumAllocatedSectionPlanes()>0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}n.push("in vec4 vColor;"),o&&(n.push("uniform float gammaFactor;"),n.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push("if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=Ze(e),u=s.getNumAllocatedSectionPlanes()>0,d=Ke(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e<t;e++)n=o.lights[e],"ambient"!==n.type&&("dir"===n.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===n.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===n.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===n.type&&"view"===n.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));p&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 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(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e<t;e++)o.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(p?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),A?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),o.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e<t;e++)n=o.lights[e],"ambient"!==n.type&&("dir"===n.type&&"world"===n.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===n.type&&("world"===n.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}c&&(p?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));r.colors&&f.push("vColor = color;");"points"===r.primitiveName&&f.push("gl_PointSize = pointSize;");u&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));l&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=o.lights.length;e<t;e++)o.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=e._material,s=e._geometry._state,r=e.scene._sectionPlanesState,o=e.scene._lightsState,n=e._material._state,a=r.getNumAllocatedSectionPlanes()>0,l=Ze(e),A=s.uvBuf,c="PhongMaterial"===n.type,h="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=Ke(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var m=0;m<r.getNumAllocatedSectionPlanes();m++)f.push("uniform bool sectionPlaneActive"+m+";"),f.push("uniform vec3 sectionPlanePos"+m+";"),f.push("uniform vec3 sectionPlaneDir"+m+";")}l&&(o.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Xe[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Xe[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e<t;e++){const t=o.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(d)for(let e=0,t=o.lights.length;e<t;e++)o.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),a){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(m=0;m<r.getNumAllocatedSectionPlanes();m++)f.push("if (sectionPlaneActive"+m+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+m+".xyz, vWorldPosition.xyz - sectionPlanePos"+m+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Xe[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Xe[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Xe[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Xe[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||h)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e<t;e++){const t=o.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),d&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),c&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(u||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}c?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),p&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},Xe={};function Ke(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,i=t.length;e<i;e++)if(t[e].castsShadow)return!0;return!1}function Ze(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}Xe[3e3]="linearToLinear",Xe[3001]="sRGBToLinear";class Je{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e<t.length;e++)s.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(s.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class Ye{constructor(e,t){this.bindTexture=function(i,s){return!!i.bind(s)&&(e.uniform1i(t,s),!0)}}}class qe{constructor(e,t){this._gl=e,this.location=t}bindArrayBuffer(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}const $e=new e({});function et(e){const t=[];let i,s;for(let r=0,o=e.length;r<o;r++)i=e[r],s=i.indexOf("/"),s>0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function tt(e){console.error(e.join("\n"))}class it{constructor(e,t){this.id=$e.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 Je(e,e.VERTEX_SHADER,et(this.source.vertex)),this._fragmentShader=new Je(e,e.FRAGMENT_SHADER,et(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void tt(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void tt(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void tt(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void tt(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void tt(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<n;++i)s=e.getActiveUniform(this.handle,i),s&&(r=s.name,"\0"===r[r.length-1]&&(r=r.substr(0,r.length-1)),o=e.getUniformLocation(this.handle,r),s.type===e.SAMPLER_2D||s.type===e.SAMPLER_CUBE||35682===s.type||e instanceof WebGL2RenderingContext&&(s.type===e.UNSIGNED_INT_SAMPLER_2D||s.type===e.INT_SAMPLER_2D)?this.samplers[r]=new Ye(e,o):this.uniforms[r]=o);const a=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<a;i++)t=e.getActiveAttrib(this.handle,i),t&&(o=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new qe(e,o));this.allocated=!0}bind(){this.allocated&&this.gl.useProgram(this.handle)}getLocation(e){if(this.allocated)return this.uniforms[e]}getAttribute(e){if(this.allocated)return this.attributes[e]}bindTexture(e,t,i){if(!this.allocated)return!1;const s=this.samplers[e];return!!s&&s.bindTexture(t,i)}destroy(){this.allocated&&($e.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}const st={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},rt=document.createElement("canvas");if(rt){const e=rt.getContext("webgl",{antialias:!0})||rt.getContext("experimental-webgl",{antialias:!0});st.WEBGL=!!e,st.WEBGL&&(st.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?st.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?st.FS_MAX_FLOAT_PRECISION="mediump":st.FS_MAX_FLOAT_PRECISION="lowp":st.FS_MAX_FLOAT_PRECISION="mediump",st.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),st.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),st.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),st.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),st.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),st.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),st.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),st.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),st.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),st.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){st.SUPPORTED_EXTENSIONS[e]=!0})))}const ot=h.vec3(),nt=new e({}),at=function(e,t){this.id=nt.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new We(t),this._allocate(t)},lt={};at.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let s=lt[i];if(!s){if(s=new at(i,e),s.errors)return console.log(s.errors.join("\n")),null;lt[i]=s,p.memory.programs++}return s._useCount++,s},at.prototype.put=function(){0==--this._useCount&&(nt.removeItem(this.id),this._program&&this._program.destroy(),delete lt[this._hash],p.memory.programs--)},at.prototype.webglContextRestored=function(){this._program=null},at.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=st.MAX_TEXTURE_UNITS,s=t.scene,r=t._material,o=s.canvas.gl,n=this._program,a=t._state,l=t._material._state,A=t._geometry._state,c=s.camera,h=t.origin,u=a.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,u&&o.depthFunc(o.LEQUAL),this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):c.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,c.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(h){const t=ze(i.dist,i.dir,h,ot);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}if(l.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=l.backfaces;e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t);const s=l.frontface;switch(e.frontface!==s&&(s?o.frontFace(o.CCW):o.frontFace(o.CW),e.frontface=s),e.lineWidth!==l.lineWidth&&(o.lineWidth(l.lineWidth),e.lineWidth=l.lineWidth),this._uPointSize&&o.uniform1f(this._uPointSize,l.pointSize),l.type){case"LambertMaterial":this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialColor&&o.uniform4f(this._uMaterialColor,l.color[0],l.color[1],l.color[2],l.alpha),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive);break;case"PhongMaterial":this._uMaterialShininess&&o.uniform1f(this._uMaterialShininess,l.shininess),this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0),r._ambientMap&&r._ambientMap._state.texture&&this._uMaterialAmbientMap&&(n.bindTexture(this._uMaterialAmbientMap,r._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMaterialAmbientMapMatrix&&o.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,r._ambientMap._state.matrix)),r._diffuseMap&&r._diffuseMap._state.texture&&this._uDiffuseMap&&(n.bindTexture(this._uDiffuseMap,r._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,r._diffuseMap._state.matrix)),r._specularMap&&r._specularMap._state.texture&&this._uSpecularMap&&(n.bindTexture(this._uSpecularMap,r._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,r._specularMap._state.matrix)),r._emissiveMap&&r._emissiveMap._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,r._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,r._emissiveMap._state.matrix)),r._alphaMap&&r._alphaMap._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,r._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,r._alphaMap._state.matrix)),r._reflectivityMap&&r._reflectivityMap._state.texture&&this._uReflectivityMap&&(n.bindTexture(this._uReflectivityMap,r._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,this._uReflectivityMapMatrix&&o.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,r._reflectivityMap._state.matrix)),r._normalMap&&r._normalMap._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,r._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,r._normalMap._state.matrix)),r._occlusionMap&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,r._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,r._occlusionMap._state.matrix)),r._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&o.uniform1f(this._uDiffuseFresnelEdgeBias,r._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&o.uniform1f(this._uDiffuseFresnelCenterBias,r._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&o.uniform3fv(this._uDiffuseFresnelEdgeColor,r._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&o.uniform3fv(this._uDiffuseFresnelCenterColor,r._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&o.uniform1f(this._uDiffuseFresnelPower,r._diffuseFresnel.power)),r._specularFresnel&&(this._uSpecularFresnelEdgeBias&&o.uniform1f(this._uSpecularFresnelEdgeBias,r._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&o.uniform1f(this._uSpecularFresnelCenterBias,r._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&o.uniform3fv(this._uSpecularFresnelEdgeColor,r._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&o.uniform3fv(this._uSpecularFresnelCenterColor,r._specularFresnel.centerColor),this._uSpecularFresnelPower&&o.uniform1f(this._uSpecularFresnelPower,r._specularFresnel.power)),r._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&o.uniform1f(this._uAlphaFresnelEdgeBias,r._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&o.uniform1f(this._uAlphaFresnelCenterBias,r._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&o.uniform3fv(this._uAlphaFresnelEdgeColor,r._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&o.uniform3fv(this._uAlphaFresnelCenterColor,r._alphaFresnel.centerColor),this._uAlphaFresnelPower&&o.uniform1f(this._uAlphaFresnelPower,r._alphaFresnel.power)),r._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&o.uniform1f(this._uReflectivityFresnelEdgeBias,r._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&o.uniform1f(this._uReflectivityFresnelCenterBias,r._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&o.uniform3fv(this._uReflectivityFresnelEdgeColor,r._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&o.uniform3fv(this._uReflectivityFresnelCenterColor,r._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&o.uniform1f(this._uReflectivityFresnelPower,r._reflectivityFresnel.power)),r._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&o.uniform1f(this._uEmissiveFresnelEdgeBias,r._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&o.uniform1f(this._uEmissiveFresnelCenterBias,r._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&o.uniform3fv(this._uEmissiveFresnelEdgeColor,r._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&o.uniform3fv(this._uEmissiveFresnelCenterColor,r._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&o.uniform1f(this._uEmissiveFresnelPower,r._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&o.uniform3fv(this._uBaseColor,l.baseColor),this._uMaterialMetallic&&o.uniform1f(this._uMaterialMetallic,l.metallic),this._uMaterialRoughness&&o.uniform1f(this._uMaterialRoughness,l.roughness),this._uMaterialSpecularF0&&o.uniform1f(this._uMaterialSpecularF0,l.specularF0),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const t=r._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(n.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uBaseColorMapMatrix&&o.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const s=r._metallicMap;s&&s._state.texture&&this._uMetallicMap&&(n.bindTexture(this._uMetallicMap,s._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicMapMatrix&&o.uniformMatrix4fv(this._uMetallicMapMatrix,!1,s._state.matrix));const a=r._roughnessMap;a&&a._state.texture&&this._uRoughnessMap&&(n.bindTexture(this._uRoughnessMap,a._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uRoughnessMapMatrix&&o.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,a._state.matrix));const A=r._metallicRoughnessMap;A&&A._state.texture&&this._uMetallicRoughnessMap&&(n.bindTexture(this._uMetallicRoughnessMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&o.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,A._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(f=r._alphaMap)&&f._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(m=r._normalMap)&&m._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,m._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialGlossiness&&o.uniform1f(this._uMaterialGlossiness,l.glossiness),this._uMaterialReflectivity&&o.uniform1f(this._uMaterialReflectivity,l.reflectivity),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const c=r._diffuseMap;c&&c._state.texture&&this._uDiffuseMap&&(n.bindTexture(this._uDiffuseMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,c._state.matrix));const h=r._specularMap;h&&h._state.texture&&this._uSpecularMap&&(n.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const u=r._glossinessMap;u&&u._state.texture&&this._uGlossinessMap&&(n.bindTexture(this._uGlossinessMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uGlossinessMapMatrix&&o.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,u._state.matrix));const g=r._specularGlossinessMap;var d,p,f,m;g&&g._state.texture&&this._uSpecularGlossinessMap&&(n.bindTexture(this._uSpecularGlossinessMap,g._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&o.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,g._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&p._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(f=r._alphaMap)&&f._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(m=r._normalMap)&&m._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,m._state.matrix))}this._lastMaterialId=l.id}if(o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),this._uColorize){const e=a.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(o.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}o.uniform3fv(this._uOffset,a.offset),A.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,A.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,A.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(A.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(A.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(A.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(A.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(A.flagsBuf),e.bindArray++),A.indicesBuf&&(A.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=A.id),A.indicesBuf?(o.drawElements(A.primitive,A.indicesBuf.numItems,A.indicesBuf.itemType,0),e.drawElements++):A.positions&&(o.drawArrays(o.TRIANGLES,0,A.positions.numItems),e.drawArrays++),u&&o.depthFunc(o.LESS)},at.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=e._material,r=t._lightsState,o=t._sectionPlanesState,n=e._material._state;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=a.getLocation("uvDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC"));const l=r.lights;let A;for(var c=0,h=l.length;c<h;c++){switch(A=l[c],A.type){case"ambient":this._uLightAmbient[c]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=null,this._uLightDir[c]=a.getLocation("lightDir"+c);break;case"point":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=null,this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c);break;case"spot":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=a.getLocation("lightDir"+c),this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c)}A.castsShadow&&(this._uShadowViewMatrix[c]=a.getLocation("shadowViewMatrix"+c),this._uShadowProjMatrix[c]=a.getLocation("shadowProjMatrix"+c))}r.lightMaps.length>0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,h=o.sectionPlanes.length;c<h;c++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+c),pos:a.getLocation("sectionPlanePos"+c),dir:a.getLocation("sectionPlaneDir"+c)});switch(this._uPointSize=a.getLocation("pointSize"),n.type){case"LambertMaterial":this._uMaterialColor=a.getLocation("materialColor"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=a.getLocation("materialAmbient"),this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=a.getLocation("materialShininess"),s._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=a.getLocation("ambientMapMatrix")),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=a.getLocation("reflectivityMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=a.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=a.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=a.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=a.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=a.getLocation("diffuseFresnelPower")),s._specularFresnel&&(this._uSpecularFresnelEdgeBias=a.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=a.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=a.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=a.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=a.getLocation("specularFresnelPower")),s._alphaFresnel&&(this._uAlphaFresnelEdgeBias=a.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=a.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=a.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=a.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=a.getLocation("alphaFresnelPower")),s._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=a.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=a.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=a.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=a.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=a.getLocation("reflectivityFresnelPower")),s._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=a.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=a.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=a.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=a.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=a.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=a.getLocation("materialBaseColor"),this._uMaterialMetallic=a.getLocation("materialMetallic"),this._uMaterialRoughness=a.getLocation("materialRoughness"),this._uMaterialSpecularF0=a.getLocation("materialSpecularF0"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),s._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=a.getLocation("baseColorMapMatrix")),s._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=a.getLocation("metallicMapMatrix")),s._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=a.getLocation("roughnessMapMatrix")),s._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=a.getLocation("metallicRoughnessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialGlossiness=a.getLocation("materialGlossiness"),this._uMaterialReflectivity=a.getLocation("reflectivityFresnel"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),s._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=a.getLocation("glossinessMapMatrix")),s._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=a.getLocation("materialSpecularGlossinessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"))}this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._aUV=a.getAttribute("uv"),this._aColor=a.getAttribute("color"),this._aFlags=a.getAttribute("flags"),this._uClippable=a.getLocation("clippable"),this._uColorize=a.getLocation("colorize"),this._uOffset=a.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},at.prototype._bindProgram=function(e){const t=st.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=i._lightsState,o=i.camera.project;let n;const a=this._program;if(a.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,s.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(var l=0,A=r.lights.length;l<A;l++)if(n=r.lights[l],this._uLightAmbient[l])s.uniform4f(this._uLightAmbient[l],n.color[0],n.color[1],n.color[2],n.intensity);else if(this._uLightColor[l]&&s.uniform4f(this._uLightColor[l],n.color[0],n.color[1],n.color[2],n.intensity),this._uLightPos[l]&&(s.uniform3fv(this._uLightPos[l],n.pos),this._uLightAttenuation[l]&&s.uniform1f(this._uLightAttenuation[l],n.attenuation)),this._uLightDir[l]&&s.uniform3fv(this._uLightDir[l],n.dir),n.castsShadow){this._uShadowViewMatrix[l]&&s.uniformMatrix4fv(this._uShadowViewMatrix[l],!1,n.getShadowViewMatrix()),this._uShadowProjMatrix[l]&&s.uniformMatrix4fv(this._uShadowProjMatrix[l],!1,n.getShadowProjMatrix());const i=n.getShadowRenderBuf();i&&(a.bindTexture("shadowMap"+l,i.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class At{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(l.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&l.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&l.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&l.push("uniform vec3 lightPos"+e+";"))}o&&(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 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;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?l.push("viewLightDir = normalize(lightDir"+e+");"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?l.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}l.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),r&&l.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&l.push("gl_PointSize = pointSize;");l.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return l.push("gl_Position = clipPos;"),l.push("}"),l}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ct=new e({}),ht=h.vec3(),ut=function(e,t){this.id=ct.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new At(t),this._allocate(t)},dt={};ut.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=dt[t];return i||(i=new ut(t,e),dt[t]=i,p.memory.programs++),i._useCount++,i},ut.prototype.put=function(){0==--this._useCount&&(ct.removeItem(this.id),this._program&&this._program.destroy(),delete dt[this._hash],p.memory.programs--)},ut.prototype.webglContextRestored=function(){this._program=null},ut.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(A){const t=ze(i.dist,i.dir,A,ht);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}if(n.id!==this._lastMaterialId){const t=n.fillColor,i=n.backfaces;e.backfaces!==i&&(i?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=i),o.uniform4f(this._uFillColor,t[0],t[1],t[2],n.fillAlpha),this._lastMaterialId=n.id}o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),o.uniform3fv(this._uOffset,a.offset),l.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(l.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(l.normalsBuf),e.bindArray++),l.indicesBuf?(l.indicesBuf.bind(),e.bindArray++):l.positionsBuf,this._lastGeometryId=l.id),l.indicesBuf?(o.drawElements(l.primitive,l.indicesBuf.numItems,l.indicesBuf.itemType,0),e.drawElements++):l.positionsBuf&&(o.drawArrays(o.TRIANGLES,0,l.positionsBuf.numItems),e.drawArrays++)},ut.prototype._allocate=function(e){const t=e.scene,i=t._lightsState,s=t._sectionPlanesState,r=t.canvas.gl;if(this._program=new it(r,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const o=this._program;this._uPositionsDecodeMatrix=o.getLocation("positionsDecodeMatrix"),this._uModelMatrix=o.getLocation("modelMatrix"),this._uModelNormalMatrix=o.getLocation("modelNormalMatrix"),this._uViewMatrix=o.getLocation("viewMatrix"),this._uViewNormalMatrix=o.getLocation("viewNormalMatrix"),this._uProjMatrix=o.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=i.lights.length;e<t;e++){switch(i.lights[e].type){case"ambient":this._uLightAmbient[e]=o.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=o.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=o.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=o.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)this._uSectionPlanes.push({active:o.getLocation("sectionPlaneActive"+e),pos:o.getLocation("sectionPlanePos"+e),dir:o.getLocation("sectionPlaneDir"+e)});this._uFillColor=o.getLocation("fillColor"),this._aPosition=o.getAttribute("position"),this._aNormal=o.getAttribute("normal"),this._uClippable=o.getLocation("clippable"),this._uGammaFactor=o.getLocation("gammaFactor"),this._uOffset=o.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=o.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ut.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t._lightsState,r=t.camera,o=r.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,i.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.normalMatrix),i.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];this._uLightAmbient[e]?i.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor)};class pt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 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;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ft=new e({}),mt=h.vec3(),gt=function(e,t){this.id=ft.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new pt(t),this._allocate(t)},_t={};gt.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=_t[t];return i||(i=new gt(t,e),_t[t]=i,p.memory.programs++),i._useCount++,i},gt.prototype.put=function(){0==--this._useCount&&(ft.removeItem(this.id),this._program&&this._program.destroy(),delete _t[this._hash],p.memory.programs--)},gt.prototype.webglContextRestored=function(){this._program=null},gt.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(a.originHash,c):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(c){const t=ze(i.dist,i.dir,c,mt);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}switch(i){case 0:n=t._xrayMaterial._state;break;case 1:n=t._highlightMaterial._state;break;case 2:n=t._selectedMaterial._state;break;default:n=t._edgeMaterial._state}if(n.id!==this._lastMaterialId){const t=n.backfaces;if(e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t),e.lineWidth!==n.edgeWidth&&(o.lineWidth(n.edgeWidth),e.lineWidth=n.edgeWidth),this._uEdgeColor){const e=n.edgeColor,t=n.edgeAlpha;o.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=n.id}let h;o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),o.uniform3fv(this._uOffset,a.offset),A.primitive===o.TRIANGLES?h=l._getEdgeIndices():A.primitive===o.LINES&&(h=A.indicesBuf),h&&(A.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,A.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(A.positionsBuf,A.compressGeometry?o.UNSIGNED_SHORT:o.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=A.id),o.drawElements(o.LINES,h.numItems,h.itemType,0),e.drawElements++)},gt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+e),pos:r.getLocation("sectionPlanePos"+e),dir:r.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=r.getLocation("edgeColor"),this._aPosition=r.getAttribute("position"),this._uClippable=r.getLocation("clippable"),this._uGammaFactor=r.getLocation("gammaFactor"),this._uOffset=r.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},gt.prototype._bindProgram=function(e){const t=this._program,i=this._scene,s=i.canvas.gl,r=i.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)};class vt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 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); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const bt=h.vec3(),yt=function(e,t){this._hash=e,this._shaderSource=new vt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},wt={};yt.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=wt[t];if(!i){if(i=new yt(t,e),i.errors)return console.log(i.errors.join("\n")),null;wt[t]=i,p.memory.programs++}return i._useCount++,i},yt.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete wt[this._hash],p.memory.programs--)},yt.prototype.webglContextRestored=function(){this._program=null},yt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(a){const t=ze(i.dist,i.dir,a,bt);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}if(o.id!==this._lastMaterialId){const t=o.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=o.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=o.id}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),n.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),n.indicesBuf&&(n.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=n.id);var l=t._state.pickID;const A=l>>24&255,c=l>>16&255,h=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,h/255,c/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},yt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uPickColor=s.getLocation("pickColor"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},yt.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class Bt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e<i.getNumAllocatedSectionPlanes();e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0;e<i.getNumAllocatedSectionPlanes();e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const xt=h.vec3(),Pt=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Bt(t),this._allocate(t)},Ct={};Pt.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Ct[t];if(!i){if(i=new Pt(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ct[t]=i,p.memory.programs++}return i._useCount++,i},Pt.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ct[this._hash],p.memory.programs--)},Pt.prototype.webglContextRestored=function(){this._program=null},Pt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,c=o.frontface,h=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(l){const t=ze(i.dist,i.dir,l,xt);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.logarithmicDepthBufferEnabled&&s.uniform1f(this._uZFar,i.camera.project.far),e.backfaces!==A&&(A?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=A),e.frontface!==c&&(c?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=c),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,a.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(u,a.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT)):this._aPosition.bindArrayBuffer(u),s.uniform2fv(this._uPickClipPos,e.pickClipPos),d.bind(),s.enableVertexAttribArray(this._aColor.location),s.vertexAttribPointer(this._aColor.location,d.itemSize,d.itemType,!0,0,0),s.drawArrays(a.primitive,0,u.numItems/3)},Pt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))};class Mt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 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;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Ft=h.vec3(),Et=function(e,t){this._hash=e,this._shaderSource=new Mt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},It={};Et.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=It[t];if(!i){if(i=new Et(t,e),i.errors)return console.log(i.errors.join("\n")),null;It[t]=i,p.memory.programs++}return i._useCount++,i},Et.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete It[this._hash],p.memory.programs--)},Et.prototype.webglContextRestored=function(){this._program=null},Et.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(a){const t=ze(i.dist,i.dir,a,Ft);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}s.uniformMatrix4fv(this._uProjMatrix,!1,l._project._state.matrix),s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),n.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),n.indicesBuf&&(n.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=n.id),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Et.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Et.prototype._bindProgram=function(e){const t=this._scene,i=t.camera.project,s=t.canvas.gl;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class Tt{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("vec4 encodeFloat( const in float depth ) {"),r.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),r.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),r.push(" vec4 comp = fract(depth * bitShift);"),r.push(" comp -= comp.xxyz * bitMask;"),r.push(" return comp;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Dt=function(e,t){this._hash=e,this._shaderSource=new Tt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},St={};Dt.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=St[i];if(!s){if(s=new Dt(i,e),s.errors)return console.log(s.errors.join("\n")),null;St[i]=s,p.memory.programs++}return s._useCount++,s},Dt.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete St[this._hash],p.memory.programs--)},Dt.prototype.webglContextRestored=function(){this._program=null},Dt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Dt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Dt.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,i.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),i.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.getNumAllocatedSectionPlanes()>0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a<l;a++)e=this._uSectionPlanes[a],t=e.active,r=s.sectionPlanes[a],t&&i.uniform1i(t,r.active),o=e.pos,o&&i.uniform3fv(e.pos,r.pos),n=e.dir,n&&i.uniform3fv(e.dir,r.dir)}};class Rt{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const Ut=h.OBB3(),Lt=h.vec4(),kt=h.vec4(),Ot=h.vec4(),Nt=h.vec3([1,0,0]),Vt=h.vec3([0,1,0]),Qt=h.vec3([0,0,1]),Ht=h.vec3(3),Gt=h.vec3(3),jt=h.identityMat4();class zt extends T{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new Rt,this._state=new ie({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:h.vec3(),origin:null,originHash:null,isUI:t.isUI}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._worldMatrix=h.identityMat4(),this._worldNormalMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const i=t.origin||t.rtcCenter;if(i&&(this._state.origin=h.vec3(i),this._state.originHash=i.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=h.identityMat4()),this.__localMatrix.set(e||jt),h.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get isUI(){return this._state.isUI}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=h.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=at.get(this),this._emphasisFillRenderer=ut.get(this),this._emphasisEdgesRenderer=gt.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=yt.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=Et.get(this))}}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=h.mat4()),h.transposeMat4(this._worldMatrix,this._worldNormalMatrix),h.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),i.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){h.transformOBB3(e,this._geometry.obb,Ut),h.OBB3ToAABB3(Ut,t);const i=this._state.offset;if(t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[0],t[4]+=i[1],t[5]+=i[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return Lt[0]=e[0],Lt[1]=e[1],Lt[2]=e[2],Lt[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Lt,kt),h.mulQuaternions(this.quaternion,kt,Ot),this.quaternion=Ot,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Lt[0]=e[0],Lt[1]=e[1],Lt[2]=e[2],Lt[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Lt,kt),h.mulQuaternions(kt,this.quaternion,kt),this}rotateX(e){return this.rotate(Nt,e)}rotateY(e){return this.rotate(Vt,e)}rotateZ(e){return this.rotate(Qt,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Ht),h.mulVec3Scalar(Ht,t,Gt),h.addVec3(this.position,Gt,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Nt,e)}translateY(e){return this.translate(Vt,e)}translateZ(e){return this.translate(Qt,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i],s=this.renderFlags;if(t.active)if(this._state.origin){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const r=0===e;s.sectionPlanesActivePerLayer[i]=r}else s.sectionPlanesActivePerLayer[i]=!0;else s.sectionPlanesActivePerLayer[i]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=at.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=at.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=ut.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=ut.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=ut.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=Et.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=Dt.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=yt.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=Pt.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,i,s){Wt(this,e,t,i,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Wt=function(){const e=h.vec3(),t=h.vec3(),i=h.vec3(),s=h.vec3(),r=h.vec3(),o=h.vec3(),n=h.vec4(),a=h.vec3(),l=h.vec3(),A=h.vec3(),c=h.vec3(),u=h.vec3(),d=h.vec3(),p=h.vec3(),f=h.vec3(),m=h.vec3(),g=h.vec4(),_=h.vec4(),v=h.vec4(),b=h.vec3(),y=h.vec3(),w=h.vec3(),B=h.vec3(),x=h.vec3(),P=h.vec3(),C=h.vec3(),M=h.vec3(),F=h.vec3(),E=h.vec3(),I=h.vec3();return function(T,D,S,R,U){var L=U.primIndex;if(null!=L&&L>-1){const V=T.geometry._state,Q=T.scene,H=Q.camera,G=Q.canvas;if("triangles"===V.primitiveName){U.primitive="triangle";const Q=L,j=V.indices,z=V.positions;let W,X,K;if(j){var k=j[Q+0],O=j[Q+1],N=j[Q+2];o[0]=k,o[1]=O,o[2]=N,U.indices=o,W=3*k,X=3*O,K=3*N}else W=3*Q,X=W+3,K=X+3;if(i[0]=z[W+0],i[1]=z[W+1],i[2]=z[W+2],s[0]=z[X+0],s[1]=z[X+1],s[2]=z[X+2],r[0]=z[K+0],r[1]=z[K+1],r[2]=z[K+2],V.compressGeometry){const e=V.positionsDecodeMatrix;e&&(he.decompressPosition(i,e,i),he.decompressPosition(s,e,s),he.decompressPosition(r,e,r))}U.canvasPos?h.canvasPosToLocalRay(G.canvas,T.origin?He(D,T.origin):D,S,R,T.worldMatrix,U.canvasPos,e,t):U.origin&&U.direction&&h.worldRayToLocalRay(T.worldMatrix,U.origin,U.direction,e,t),h.normalizeVec3(t),h.rayPlaneIntersect(e,t,i,s,r,n),U.localPos=n,U.position=n,g[0]=n[0],g[1]=n[1],g[2]=n[2],g[3]=1,h.transformVec4(T.worldMatrix,g,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],U.canvasPos&&T.origin&&(a[0]+=T.origin[0],a[1]+=T.origin[1],a[2]+=T.origin[2]),U.worldPos=a,h.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],U.viewPos=l,h.cartesianToBarycentric(n,i,s,r,A),U.bary=A;const Z=V.normals;if(Z){if(V.compressGeometry){const e=3*k,t=3*O,i=3*N;he.decompressNormal(Z.subarray(e,e+2),c),he.decompressNormal(Z.subarray(t,t+2),u),he.decompressNormal(Z.subarray(i,i+2),d)}else c[0]=Z[W],c[1]=Z[W+1],c[2]=Z[W+2],u[0]=Z[X],u[1]=Z[X+1],u[2]=Z[X+2],d[0]=Z[K],d[1]=Z[K+1],d[2]=Z[K+2];const e=h.addVec3(h.addVec3(h.mulVec3Scalar(c,A[0],b),h.mulVec3Scalar(u,A[1],y),w),h.mulVec3Scalar(d,A[2],B),x);U.worldNormal=h.normalizeVec3(h.transformVec3(T.worldNormalMatrix,e,P))}const J=V.uv;if(J){if(p[0]=J[2*k],p[1]=J[2*k+1],f[0]=J[2*O],f[1]=J[2*O+1],m[0]=J[2*N],m[1]=J[2*N+1],V.compressGeometry){const e=V.uvDecodeMatrix;e&&(he.decompressUV(p,e,p),he.decompressUV(f,e,f),he.decompressUV(m,e,m))}U.uv=h.addVec3(h.addVec3(h.mulVec2Scalar(p,A[0],C),h.mulVec2Scalar(f,A[1],M),F),h.mulVec2Scalar(m,A[2],E),I)}}}}}();class Xt extends T{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Kt={opaque:0,mask:1,blend:2},Zt=["opaque","mask","blend"];class Jt extends Xt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({type:"PhongMaterial",ambient:h.vec3([1,1,1]),diffuse:h.vec3([1,1,1]),specular:h.vec3([1,1,1]),emissive:h.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=Kt[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 Zt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}function Yt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}function qt(e,t,i=null){let s;const r=t;if(1009===r)return e.UNSIGNED_BYTE;if(1017===r)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===r)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===r)return e.BYTE;if(1011===r)return e.SHORT;if(1012===r)return e.UNSIGNED_SHORT;if(1013===r)return e.INT;if(1014===r)return e.UNSIGNED_INT;if(1015===r)return e.FLOAT;if(1016===r)return e.HALF_FLOAT;if(1021===r)return e.ALPHA;if(1023===r)return e.RGBA;if(1024===r)return e.LUMINANCE;if(1025===r)return e.LUMINANCE_ALPHA;if(1026===r)return e.DEPTH_COMPONENT;if(1027===r)return e.DEPTH_STENCIL;if(1028===r)return e.RED;if(1022===r)return e.RGBA;if(1029===r)return e.RED_INTEGER;if(1030===r)return e.RG;if(1031===r)return e.RG_INTEGER;if(1033===r)return e.RGBA_INTEGER;if(33776===r||33777===r||33778===r||33779===r)if(3001===i){const t=Yt(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===r)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(s=Yt(e,"WEBGL_compressed_texture_s3tc"),null===s)return null;if(33776===r)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===r)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===r)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===r)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===r||35841===r||35842===r||35843===r){const t=Yt(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===r)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===r)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===r)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===r)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===r){const t=Yt(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){const t=Yt(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===r)return 3001===i?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===r||37809===r||37810===r||37811===r||37812===r||37813===r||37814===r||37815===r||37816===r||37817===r||37818===r||37819===r||37820===r||37821===r){const t=Yt(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===r){const t=Yt(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===r)return 3001===i?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===r?e.UNSIGNED_INT_24_8:1e3===r?e.REPEAT:1001===r?e.CLAMP_TO_EDGE:1004===r||1005===r?e.NEAREST_MIPMAP_LINEAR:1007===r?e.LINEAR_MIPMAP_NEAREST:1008===r?e.LINEAR_MIPMAP_LINEAR:1003===r?e.NEAREST:1006===r?e.LINEAR:null}const $t=new Uint8Array([0,0,0,1]);class ei{constructor({gl:e,target:t,format:i,type:s,wrapS:r,wrapT:o,wrapR:n,encoding:a,preloadColor:l,premultiplyAlpha:A,flipY:c}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=i||1023,this.type=s||1009,this.internalFormat=null,this.premultiplyAlpha=!!A,this.flipY=!!c,this.unpackAlignment=4,this.wrapS=r||1e3,this.wrapT=o||1e3,this.wrapR=n||1e3,this.encoding=a||3001,this.texture=e.createTexture(),l&&this.setPreloadColor(l),this.allocated=!0}setPreloadColor(e){e?($t[0]=Math.floor(255*e[0]),$t[1]=Math.floor(255*e[1]),$t[2]=Math.floor(255*e[2]),$t[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):($t[0]=0,$t[1]=0,$t[2]=0,$t[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let i=0,s=e.length;i<s;i++)t.texImage2D(e[i],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,$t)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,$t);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let s=!1;i.bindTexture(this.target,this.texture);const r=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);const o=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const n=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);const a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const l=qt(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(s=!0);const A=qt(i,this.magFilter);A&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,A);const c=qt(i,this.wrapS);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,c);const h=qt(i,this.wrapT);h&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,h);const u=qt(i,this.format,this.encoding),d=qt(i,this.type),p=ti(i,this.internalFormat,u,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(_.isArray(e)){const t=e,s=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,r=s.length;e<r;e++)i.texImage2D(s[e],0,p,u,d,t[e])}}else i.texImage2D(i.TEXTURE_2D,0,p,u,d,e);s&&i.generateMipmap(this.target),i.bindTexture(this.target,null),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,r),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o),i.pixelStorei(i.UNPACK_ALIGNMENT,n),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,a)}setCompressedData({mipmaps:e,props:t={}}){const i=this.gl,s=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),i.activeTexture(i.TEXTURE0+0),i.bindTexture(this.target,this.texture);let r=e.length>1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=qt(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=qt(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=qt(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ii(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ii(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,qt(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,qt(i,this.magFilter)));const a=qt(i,this.format,this.encoding),l=qt(i,this.type),A=ti(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t<s;t++){const s=e[t];1023!==this.format?null!==a?i.compressedTexSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,a,s.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):i.texSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,a,l,s.data)}i.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const i=qt(t,e.minFilter);i&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,i),i!==t.NEAREST_MIPMAP_NEAREST&&i!==t.LINEAR_MIPMAP_NEAREST&&i!==t.NEAREST_MIPMAP_LINEAR&&i!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const i=qt(t,e.magFilter);i&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,i))}if(void 0!==e.wrapS){const i=qt(t,e.wrapS);i&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,i))}if(void 0!==e.wrapT){const i=qt(t,e.wrapT);i&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,i))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function ti(e,t,i,s,r,o=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let n=i;return i===e.RED&&(s===e.FLOAT&&(n=e.R32F),s===e.HALF_FLOAT&&(n=e.R16F),s===e.UNSIGNED_BYTE&&(n=e.R8)),i===e.RG&&(s===e.FLOAT&&(n=e.RG32F),s===e.HALF_FLOAT&&(n=e.RG16F),s===e.UNSIGNED_BYTE&&(n=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(n=e.RGBA32F),s===e.HALF_FLOAT&&(n=e.RGBA16F),s===e.UNSIGNED_BYTE&&(n=3001===r&&!1===o?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(n=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(n=e.RGB5_A1)),n!==e.R16F&&n!==e.R32F&&n!==e.RG16F&&n!==e.RG32F&&n!==e.RGBA16F&&n!==e.RGBA32F||Yt(e,"EXT_color_buffer_float"),n}function ii(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function si(e){if(!ri(e.width)||!ri(e.height)){const t=document.createElement("canvas");t.width=oi(e.width),t.height=oi(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function ri(e){return 0==(e&e-1)}function oi(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class ni extends T{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new ie({texture:new ei({gl:this.scene.canvas.gl}),matrix:h.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=h.vec2([0,0]),this._scale=h.vec2([1,1]),this._rotate=h.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 ei({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=h.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=h.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?h.mulMat4(t,i):i),0!==this._rotate&&(i=h.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?h.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=si(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=si(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const ai=h.vec3(),li=h.vec3();h.vec3();const Ai=h.vec3([0,-1,0]),ci=h.vec4([0,0,0,1]);class hi extends Xt{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({type:"LambertMaterial",ambient:h.vec3([1,1,1]),color:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const ui={opaque:0,mask:1,blend:2},di=["opaque","mask","blend"];class pi extends Xt{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({type:"MetallicMaterial",baseColor:h.vec4([1,1,1]),emissive:h.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=ui[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 di[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const fi={opaque:0,mask:1,blend:2},mi=["opaque","mask","blend"];class gi extends Xt{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({type:"SpecularMaterial",diffuse:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),specular:h.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=fi[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 mi[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const _i={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 vi extends Xt{get type(){return"EmphasisMaterial"}get presets(){return _i}constructor(e,t={}){super(e,t),this._state=new ie({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),e=e||"default",this._preset===e)return;const t=_i[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(_i).join(", "))}get preset(){return console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),this._preset}destroy(){super.destroy(),this._state.destroy()}}const bi={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 yi extends Xt{get type(){return"EdgeMaterial"}get presets(){return bi}constructor(e,t={}){super(e,t),this._state=new ie({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=bi[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(bi).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}class wi extends T{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=h.vec3(t.pos||[0,0,0]),this._up=h.vec3(t.up||[0,1,0]),this._normal=h.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=h.vec3(),this._rtcPos=h.vec3(),this._imageSize=h.vec2(),this._texture=new ni(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 Ne(this,{matrix:h.inverseMat4(h.lookAtMat4v(this._pos,h.subVec3(this._pos,this._normal,h.mat4()),this._up,h.mat4())),children:[this._bitmapMesh=new zt(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new pe(this,Be({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const Bi=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let o=0;o<3;o++)if(s=t[3*e+o],r=t[3*i+o],s!==r)return r-s;return 0}let o=e.slice().sort(r),n=null;for(let e=0,t=o.length;e<t;e++)0!==e&&0===r(o[e],o[e-1])||(n=o[e]),i[o[e]]=n;for(let t=0,r=e.length;t<r;t+=3){const r=i[e[t]],o=i[e[t+1]],n=i[e[t+2]];let a=r,l=o,A=n;if(r>o&&r>n?o>n?(a=r,l=o,A=n):(a=r,l=n,A=o):o>r&&o>n?r>n?(a=o,l=r,A=n):(a=o,l=n,A=r):n>r&&n>o&&(r>o?(a=n,l=r,A=o):(a=n,l=o,A=r)),s[t+0]=[a,l],s[t+1]=[l,A],a>A){const e=A;A=a,a=e}s[t+2]=[A,a]}function a(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(a);let l=0;for(let e=0;e<s.length;e++)if(0===e||0!==a(s[e],s[e-1])){if(0!==e&&2!==l)return!1;l=1}else l++;return!(s.length>0&&2!==l)},xi=h.vec3(),Pi=h.vec3(),Ci=h.vec3();class Mi{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!Bi(t,e))return-1;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],o=3*t[s+1],n=3*t[s+2];xi[0]=e[r],xi[1]=e[r+1],xi[2]=e[r+2],Pi[0]=e[o],Pi[1]=e[o+1],Pi[2]=e[o+2],Ci[0]=e[n],Ci[1]=e[n+1],Ci[2]=e[n+2],h.cross3Vec3(xi,Pi,xi),i+=h.dotVec3(xi,Ci)}return i/6}}const Fi=new Mi,Ei=h.vec3(),Ii=h.vec3(),Ti=h.vec3(),Di=h.vec3(),Si=h.vec3(),Ri=h.vec3();class Ui{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get surfaceArea(){const e=this.vertices,t=this.indices;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],o=3*t[s+1],n=3*t[s+2];Ei[0]=e[r],Ei[1]=e[r+1],Ei[2]=e[r+2],Ii[0]=e[o],Ii[1]=e[o+1],Ii[2]=e[o+2],Ti[0]=e[n],Ti[1]=e[n+1],Ti[2]=e[n+2],h.subVec3(Ei,Ii,Di),h.subVec3(Ti,Ii,Si),i+=.5*h.lenVec3(h.cross3Vec3(Di,Si,Ri))}return i}}const Li=new Ui,ki=h.OBB3(),Oi=h.OBB3(),Ni=h.OBB3();class Vi{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=h.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this),this._volume=null,this._surfaceArea=null}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex&&this.layer.getEachVertex(this.portionId,e)}getEachIndex(e){this.layer.getEachIndex&&this.layer.getEachIndex(this.portionId,e)}isSolid(){return this.layer.solid}get volume(){if(null!==this._volume)return this._volume;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Fi.reset(),Fi.setPrimitive(this.layer.primitive),this.getEachVertex((e=>{Fi.addVertex(e)})),this.getEachIndex((e=>{Fi.addIndex(e)})),this._volume=Fi.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Li.reset(),this.getEachVertex((e=>{Li.addVertex(e)})),this.getEachIndex((e=>{Li.addIndex(e)})),this._surfaceArea=Li.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(h.AABB3ToOBB3(this._aabbLocal,ki),this.transform?(h.transformOBB3(this.transform.worldMatrix,ki,Oi),h.transformOBB3(this.model.worldMatrix,Oi,Ni),h.OBB3ToAABB3(Ni,this._aabbWorld)):(h.transformOBB3(this.model.worldMatrix,ki,Oi),h.OBB3ToAABB3(Oi,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const Qi=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let Hi=0;const Gi=1,ji=4,zi=8,Wi=16,Xi=32,Ki=256,Zi=512,Ji=1024,Yi=2048,qi={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},$i=new Float32Array([1,1,1,1]),es=new Float32Array([0,0,0,1]),ts=h.vec4(),is=h.vec3(),ss=h.vec3(),rs=h.mat4();class os{constructor(e,t=!1,{instancing:i=!1,edges:s=!1,useAlphaCutoff:r=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._useAlphaCutoff=r,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t<o;t++){const r=this._uSectionPlanes[t];if(r)if(t<n){const o=A.sectionPlanesActivePerLayer[l+t];if(i.uniform1i(r.active,o?1:0),o){const o=a[t],n=e._state.origin;if(n){const e=ze(o.dist,o.dir,n,is,s.matrix);i.uniform3fv(r.pos,e)}else i.uniform3fv(r.pos,o.pos);i.uniform3fv(r.dir,o.dir)}}else i.uniform1i(r.active,0)}}}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uColor||(this._uColor=s.getLocation("silhouetteColor")),this._uUVDecodeMatrix=s.getLocation("uvDecodeMatrix"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uGammaFactor=s.getLocation("gammaFactor"),t.uniformBlockBinding(s.handle,t.getUniformBlockIndex(s.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=s.getLocation("zFar")),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aUV=s.getAttribute("uv"),this._aColor=s.getAttribute("color"),this._aMetallicRoughness=s.getAttribute("metallicRoughness"),this._aFlags=s.getAttribute("flags"),this._aPickColor=s.getAttribute("pickColor"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrix=s.getAttribute("modelMatrix"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=s.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=s.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=s.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),this._useAlphaCutoff&&(this._alphaCutoffLocation=s.getLocation("materialAlphaCutoff")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=s.getLocation("intensityRange")),this._uPointSize=s.getLocation("pointSize"),this._uNearPlaneHeight=s.getLocation("nearPlaneHeight"),e.crossSections&&(this._uSliceColor=s.getLocation("sliceColor"),this._uSliceThickness=s.getLocation("sliceThickness"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState,o=r.lights;s.bind(),e.textureUnit=0,this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,r.getAmbientColorAndIntensity()),this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor);for(let e=0,t=o.length;e<t;e++){const t=o[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}}_makeVAO(e){const t=this._scene.canvas.gl,i=t.createVertexArray();return t.bindVertexArray(i),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer(e.positionsBuf),this._aUV&&this._aUV.bindArrayBuffer(e.uvBuf),this._aNormal&&this._aNormal.bindArrayBuffer(e.normalsBuf),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer(e.colorsBuf),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges&&e.edgeIndicesBuf?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),i}drawLayer(e,t,i,{colorUniform:s=!1,incrementDrawState:r=!1}={}){const o=st.MAX_TEXTURE_IMAGE_UNITS,n=this._scene,a=n.canvas.gl,{_state:l,model:A}=t,{textureSet:c,origin:u,positionsDecodeMatrix:d}=l,p=n._lightsState,f=n.pointsMaterial,{camera:m}=A.scene,{viewNormalMatrix:g,project:_}=m,v=e.pickViewMatrix||m.viewMatrix,{position:b,rotationMatrix:y,worldNormalMatrix:w}=A;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?a.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));let B=0;const x=16;this._matricesUniformBlockBufferData.set(y,0);const P=0!==u[0]||0!==u[1]||0!==u[2],C=0!==b[0]||0!==b[1]||0!==b[2];if(P||C){const e=is;if(P){const t=h.transformPoint3(y,u,ss);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=b[0],e[1]+=b[1],e[2]+=b[2],this._matricesUniformBlockBufferData.set(He(v,e,rs),B+=x)}else this._matricesUniformBlockBufferData.set(v,B+=x);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||_.matrix,B+=x),this._matricesUniformBlockBufferData.set(d,B+=x),this._matricesUniformBlockBufferData.set(w,B+=x),this._matricesUniformBlockBufferData.set(g,B+=x),a.bindBuffer(a.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),a.bufferData(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,a.DYNAMIC_DRAW),a.bindBufferBase(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),a.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),n.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&a.uniform1f(this._uZFar,n.camera.project.far)}if(this._uPickInvisible&&a.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&a.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&a.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&a.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&a.uniform2f(this._uDrawingBufferSize,a.drawingBufferWidth,a.drawingBufferHeight),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._uIntensityRange&&f.filterIntensity&&a.uniform2f(this._uIntensityRange,f.minIntensity,f.maxIntensity),this._uPointSize&&a.uniform1f(this._uPointSize,f.pointSize),this._uNearPlaneHeight){const e="ortho"===n.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*n.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,e)}if(c){const{colorTexture:t,metallicRoughnessTexture:i,emissiveTexture:s,normalsTexture:r,occlusionTexture:n}=c;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uMetallicRoughMap&&i&&(this._program.bindTexture(this._uMetallicRoughMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uEmissiveMap&&s&&(this._program.bindTexture(this._uEmissiveMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uNormalMap&&r&&(this._program.bindTexture(this._uNormalMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uAOMap&&n&&(this._program.bindTexture(this._uAOMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o)}if(p.reflectionMaps.length>0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;ts[0]=i,ts[1]=s,ts[2]=t.blendCutoff,ts[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,ts),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(this._useAlphaCutoff&&a.uniform1f(this._alphaCutoffLocation,c.alphaCutoff),s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===qi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===qi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===qi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?es:$i)}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 ns extends os{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!1,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)i.edgeIndicesBuf&&t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class as extends ns{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++)r=i.lights[e],"ambient"!==r.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===r.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")));o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e<t;e++)if(r=i.lights[e],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?o.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return o.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),o.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;")),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?(s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;")):(s.push(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class ls extends ns{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";");r.push("uniform float sliceThickness;"),r.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;");for(let e=0,i=t.lights.length;e<i;e++){const i=t.lights[e];"ambient"!==i.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec4 newColor;"),r.push(" newColor = vColor;"),s){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e<i;e++){const i=t.lights[e];if("ambient"!==i.type){if("dir"===i.type)"view"===i.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?r.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled?r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(r.push(" float dx = dFdx(gl_FragCoord.z);"),r.push(" float dy = dFdy(gl_FragCoord.z);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = gl_FragCoord.z + diff;")),r.push("}"),r}}class As extends ns{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");o.push("uniform float sliceThickness;"),o.push("uniform vec4 sliceColor;")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),o.push(" vec4 newColor;"),o.push(" newColor = vColor;"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class cs extends ns{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class hs extends cs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class us extends cs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ds extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class ps extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class fs extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),s.push("}"),s}}class ms extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push(" if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class gs extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec2 vHighPrecisionZW;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class _s extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class vs extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 encodeFloat( const in float v ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(v * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class bs extends ns{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),o&&n.push("in vec4 vClipPosition;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),n.push(" return surf_norm;"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");o?(n.push(" if (dist > (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),n.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return n.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),n.push("float aoFactor = texture(uAOMap, vUV).r;"),n.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),n.push("vec4 fragColor;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):n.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&n.push("fragColor = linearToGamma(fragColor, gammaFactor);"),n.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class ys extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),s.push("}"),s}}class ws extends ns{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(o&&n.push("uniform float materialAlphaCutoff;"),n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return n.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),n.push("vec4 sampleColor = texture(uColorMap, vUV);"),o&&(n.push("if (sampleColor.a < materialAlphaCutoff) {"),n.push(" discard;"),n.push("}")),t&&n.push("sampleColor = sRGBToLinear(sampleColor);"),n.push("vec4 colorTexel = color * sampleColor;"),n.push("float opacity = color.a;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):n.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&n.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}const Bs=h.vec3(),xs=h.vec3(),Ps=h.vec3(),Cs=h.vec3(),Ms=h.mat4();class Fs extends os{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=Bs;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=xs;if(l){const e=Ps;h.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Ms),m=Cs,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Es=h.vec3(),Is=h.vec3(),Ts=h.vec3(),Ds=h.vec3(),Ss=h.mat4();class Rs extends os{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=Es;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Is;if(l){const e=Ts;h.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Ss),m=Ds,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Us{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new As(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ds(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ps(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Fs(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Rs(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new as(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new as(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new ls(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new ls(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ws(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ws(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new ws(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new ws(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new bs(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new bs(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new As(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new gs(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new _s(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new hs(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new us(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ds(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new fs(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new ys(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ps(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ms(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new vs(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Rs(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Fs(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ls={};let ks=65536,Os=5e6;class Ns{constructor(){}set doublePrecisionEnabled(e){h.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return h.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),ks=e}get maxDataTextureHeight(){return ks}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Os=e}get maxGeometryBatchSize(){return Os}}const Vs=new Ns;class Qs{constructor(e=Vs.maxGeometryBatchSize){this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Hs=h.mat4(),Gs=h.mat4();function js(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,c=t[5]-a,u=65525,d=u/l,p=u/A,f=u/c,m=e=>e>=0?e:0;for(let t=0;t<s;t+=3)r[t+0]=Math.floor(m(e[t+0]-o)*d),r[t+1]=Math.floor(m(e[t+1]-n)*p),r[t+2]=Math.floor(m(e[t+2]-a)*f);return h.identityMat4(Hs),h.translationMat4v(t,Hs),h.identityMat4(Gs),h.scalingMat4v([l/u,A/u,c/u],Gs),h.mulMat4(Hs,Gs,i),r}function zs(e,t){const i=e[0],s=e[1],r=e[2],o=e[3]-i,n=e[4]-s,a=e[5]-r,l=65525;return h.identityMat4(Hs),h.translationMat4v(e,Hs),h.identityMat4(Gs),h.scalingMat4v([o/l,n/l,a/l],Gs),h.mulMat4(Hs,Gs,t),t}function Ws(e,t,i){let s=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),r=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=s,t=r;e=(1-Math.abs(r))*(s>=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function Xs(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Ks=h.mat4(),Zs=h.mat4(),Js=h.vec4([0,0,0,1]),Ys=h.vec3(),qs=h.vec3(),$s=h.vec3(),er=h.vec3(),tr=h.vec3(),ir=h.vec3(),sr=h.vec3();class rr{constructor(e){this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ls[t];return i||(i=new Us(e),Ls[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ls[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Qs(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new ie({origin:h.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=h.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=h.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=h.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=h.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=t.positions,s=t.positionsCompressed,r=t.normals,o=t.normalsCompressed,n=t.uv,a=t.uvCompressed,l=t.colors,A=t.colorsCompressed,c=t.indices,u=t.edgeIndices,d=t.color,p=t.metallic,f=t.roughness,m=t.opacity,g=t.meshMatrix,_=t.pickColor,v=this.model.scene,b=this._buffer,y=b.positions.length/3;let w;if(h.expandAABB3(this._modelAABB,t.aabb),this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";w=s.length/3;for(let e=0,t=s.length;e<t;e++)b.positions.push(s[e])}else{if(!i)throw"positions expected";w=i.length/3;for(let e=0,t=i.length;e<t;e++)b.positions.push(i[e])}if(o&&o.length>0)for(let e=0,t=o.length;e<t;e++)b.normals.push(o[e]);else if(r&&r.length>0){const e=Ks;g?h.inverseMat4(h.transposeMat4(g,Zs),e):h.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,c,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;u<i;u+=3)d[0]=t[u],d[1]=t[u+1],d[2]=t[u+2],h.transformVec3(e,d,p),h.normalizeVec3(p,p),l=n=Ws(p,"floor","floor"),a=Xs(n),A=c=o(p,a),n=Ws(p,"ceil","floor"),a=Xs(n),A=o(p,a),A>c&&(l=n,c=A),n=Ws(p,"floor","ceil"),a=Xs(n),A=o(p,a),A>c&&(l=n,c=A),n=Ws(p,"ceil","ceil"),a=Xs(n),A=o(p,a),A>c&&(l=n,c=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)b.colors.push(255*l[e]),b.colors.push(255*l[e+1]),b.colors.push(255*l[e+2]),b.colors.push(255);else if(A)for(let e=0,t=l.length;e<t;e+=3)b.colors.push(l[e]),b.colors.push(l[e+1]),b.colors.push(l[e+2]),b.colors.push(255);else if(d){const e=d[0],t=d[1],i=d[2],s=m;for(let r=0;r<w;r++)b.colors.push(e),b.colors.push(t),b.colors.push(i),b.colors.push(s)}const B=null!=p?p:0,x=null!=f?f:255;for(let e=0;e<w;e++)b.metallicRoughness.push(B),b.metallicRoughness.push(x);if(n&&n.length>0)for(let e=0,t=n.length;e<t;e++)b.uv.push(n[e]);else if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)b.uv.push(a[e]);for(let e=0,t=c.length;e<t;e++)b.indices.push(y+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)b.edgeIndices.push(y+u[e]);{const e=b.pickColors.length;for(let t=e,i=e+4*w;t<i;t+=4)b.pickColors.push(_[0]),b.pickColors.push(_[1]),b.pickColors.push(_[2]),b.pickColors.push(_[3])}if(v.entityOffsetsEnabled)for(let e=0;e<w;e++)b.offsets.push(0),b.offsets.push(0),b.offsets.push(0);const P=this._portions.length,C={vertsBaseIndex:y,numVerts:w,indicesBaseIndex:b.indices.length-c.length,numIndices:c.length};return v.readableGeometryEnabled&&(C.indices=c,v.entityOffsetsEnabled&&(C.offset=new Float32Array(3))),this._portions.push(C),this._numPortions++,this.model.numPortions++,this._numVerts+=C.numVerts,this._meshes.push(e),P}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):js(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=h.mat4());if(e.positionsBuf=new se(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],i=3*t.vertsBaseIndex,r=i+3*t.numVerts;t.quantizedPositions=s.slice(i,r)}}if(i.normals.length>0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new se(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new se(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new se(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=he.getUVBounds(i.uv),r=he.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=h.mat3(r.decodeMatrix),e.uvBuf=new se(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new se(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new se(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new se(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new se(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],c=t[3];for(let e=0;e<o;e+=4)n[e+0]=a,n[e+1]=l,n[e+2]=A,n[e+3]=c;this._state.colorsBuf&&this._state.colorsBuf.setData(n,r,o)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=e,o=this._portions[r],n=o.vertsBaseIndex,a=o.numVerts,l=!!(t&Gi),A=!!(t&Ki),c=!!(t&Zi),h=!!(t&Ji),u=!!(t&Yi),d=!!(t&zi),p=!!(t&ji);let f,m;f=!l||p||A||c&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,m=!l||p?qi.NOT_RENDERED:h?qi.SILHOUETTE_SELECTED:c?qi.SILHOUETTE_HIGHLIGHTED:A?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let g=0;g=!l||p?qi.NOT_RENDERED:h?qi.EDGES_SELECTED:c?qi.EDGES_HIGHLIGHTED:A?qi.EDGES_XRAYED:u?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let _=l&&!p&&d?qi.PICK:qi.NOT_RENDERED;const v=t&Wi?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=n,t=n+a;e<t;e++){let t=0;t|=f,t|=m<<4,t|=g<<8,t|=_<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(a);for(let t=0;t<a;t++){let i=0;i|=f,i|=m<<4,i|=g<<8,i|=_<<12,i|=v<<16,e[t]=i}this._state.flagsBuf.setData(e,n,a)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=e,s=this._portions[i],r=3*s.vertsBaseIndex,o=3*s.numVerts,n=this._scratchMemory.getFloat32Array(o),a=t[0],l=t[1],A=t[2];for(let e=0;e<o;e+=3)n[e+0]=a,n[e+1]=l,n[e+2]=A;this._state.offsetsBuf&&this._state.offsetsBuf.setData(n,r,o),this.model.scene.readableGeometryEnabled&&(s.offset[0]=t[0],s.offset[1]=t[1],s.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portions[e];if(!s)return void this.model.error("portion not found: "+e);const r=s.quantizedPositions,o=this.model.matrix,n=h.vec4();n.set(i.origin,0),n[3]=1,h.mulMat4v4(o,n,n);const a=n[0],l=n[1],A=n[2],c=Js,u=i.positionsDecodeMatrix;for(let e=0,i=r.length;e<i;e+=3)c[0]=r[e],c[1]=r[e+1],c[2]=r[e+2],c[3]=1,h.decompressPosition(c,u),c[3]=1,h.mulMat4v4(o,c,c),c[0]+=a,c[1]+=l,c[2]+=A,t(c)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const s=i.indices;for(let e=0,i=s.length;e<i;e++)t(s[e])}getElementsCountAndOffset(e){let t=null,i=null;const s=this._portions[e];return s&&(t=s.numIndices,i=s.indicesBaseIndex),{count:t,offset:i}}readGeometryData(e){if(!this._finalized)throw"Not finalized";const t=this._portions[e],i=this._state,s=this.model.matrix,r=i.positionsDecodeMatrix,o=h.vec4();o.set(i.origin,0),o[3]=1,h.mulMat4v4(s,o,o);const n=i.indicesBuf.getData(t.indicesBaseIndex,t.numIndices).map((e=>e-t.vertsBaseIndex)),a=h.mulMat4(s,r,new Array(16));a[12]+=o[0],a[13]+=o[1],a[14]+=o[2];const l=i.positionsBuf.getData(t.vertsBaseIndex,t.numVerts);return{indices:n,positions:h.transformPositions3(a,l,new Array(l.length))}}drawColorOpaque(e,t){if(this._numCulledLayerPortions===this._numPortions||0===this._numVisibleLayerPortions||this._numTransparentLayerPortions===this._numPortions||this._numXRayedLayerPortions===this._numPortions)return;this._updateBackfaceCull(e,t);const i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){if(this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions)if(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported)this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT);else if(t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported){this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}else this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,qi.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK))}precisionRayPickSurface(e,t,i,s,r){if(!this.model.scene.readableGeometryEnabled)return!1;const o=this._state,n=this._portions[e];if(!n)return this.model.error("portion not found: "+e),!1;const a=n.quantizedPositions,l=n.indices,A=o.origin,c=n.offset,u=Ys,d=qs;u.set(A?h.subVec3(t,A,$s):t),d.set(i),c&&h.subVec3(u,c),h.transformRay(this.model.worldNormalMatrix,u,d,u,d);const p=er,f=tr,m=ir;let g=!1,_=0;const v=sr;for(let e=0,i=l.length;e<i;e+=3){const i=3*l[e],n=3*l[e+1],b=3*l[e+2];if(p[0]=a[i],p[1]=a[i+1],p[2]=a[i+2],f[0]=a[n],f[1]=a[n+1],f[2]=a[n+2],m[0]=a[b],m[1]=a[b+1],m[2]=a[b+2],h.decompressPosition(p,o.positionsDecodeMatrix),h.decompressPosition(f,o.positionsDecodeMatrix),h.decompressPosition(m,o.positionsDecodeMatrix),h.rayTriangleIntersect(u,d,p,f,m,v)){h.transformPoint3(this.model.worldMatrix,v,v),c&&h.addVec3(v,c),A&&h.addVec3(v,A);const e=Math.abs(h.lenVec3(h.subVec3(v,t,[])));(!g||e>_)&&(_=e,s.set(v),r&&h.triangleNormal(p,f,m,r),g=!0)}}return g&&r&&(h.transformVec3(this.model.worldNormalMatrix,r,r),h.normalizeVec3(r)),g}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class or extends os{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!0,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?i.edgeIndicesBuf&&t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class nr extends or{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r<o;r++)n=i.lights[r],"ambient"!==n.type&&(a.push("uniform vec4 lightColor"+r+";"),"dir"===n.type&&a.push("uniform vec3 lightDir"+r+";"),"point"===n.type&&a.push("uniform vec3 lightPos"+r+";"),"spot"===n.type&&(a.push("uniform vec3 lightPos"+r+";"),a.push("uniform vec3 lightDir"+r+";")));for(a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r<o;r++)if(n=i.lights[r],"ambient"!==n.type){if("dir"===n.type)"view"===n.space?a.push("viewLightDir = normalize(lightDir"+r+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);");else if("point"===n.type)"view"===n.space?a.push("viewLightDir = -normalize(lightPos"+r+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+r+", 0.0)).xyz);");else{if("spot"!==n.type)continue;"view"===n.space?a.push("viewLightDir = normalize(lightDir"+r+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+r+".rgb * lightColor"+r+".a);")}return a.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?(s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;")):(s.push(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class ar 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,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}for(this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;"),s=0,r=i.lights.length;s<r;s++){const e=i.lights[s];"ambient"!==e.type&&(n.push("uniform vec4 lightColor"+s+";"),"dir"===e.type&&n.push("uniform vec3 lightDir"+s+";"),"point"===e.type&&n.push("uniform vec3 lightPos"+s+";"),"spot"===e.type&&(n.push("uniform vec3 lightPos"+s+";"),n.push("uniform vec3 lightDir"+s+";")))}if(n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),o){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s<r;s++){const e=i.lights[s];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?n.push("viewLightDir = normalize(lightDir"+s+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+s+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?n.push("viewLightDir = -normalize(lightPos"+s+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+s+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?n.push("viewLightDir = normalize(lightDir"+s+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+s+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+s+".rgb * lightColor"+s+".a);")}}return n.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):n.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled?n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(n.push(" float dx = dFdx(gl_FragCoord.z);"),n.push(" float dy = dFdy(gl_FragCoord.z);"),n.push(" float diff = sqrt(dx*dx+dy*dy);"),n.push(" gl_FragDepth = gl_FragCoord.z + diff;")),n.push("}"),n}}class lr extends or{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class Ar extends or{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class cr extends Ar{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class hr extends Ar{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ur extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class dr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class pr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),s.push("}"),s}}class fr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class mr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("in vec2 vHighPrecisionZW;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class gr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class _r extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const vr={3e3:"linearToLinear",3001:"sRGBToLinear"};class br extends or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),o&&n.push("in vec4 vClipPosition;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+vr[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+vr[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");o?(n.push(" if (dist > (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),n.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return n.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),n.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),n.push("vec4 fragColor;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):n.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&n.push("fragColor = linearToGamma(fragColor, gammaFactor);"),n.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class yr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),s.push("}"),s}}class wr extends or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(o&&n.push("uniform float materialAlphaCutoff;"),n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return n.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),n.push("vec4 sampleColor = texture(uColorMap, vUV);"),o&&(n.push("if (sampleColor.a < materialAlphaCutoff) {"),n.push(" discard;"),n.push("}")),t&&n.push("sampleColor = sRGBToLinear(sampleColor);"),n.push("vec4 colorTexel = color * sampleColor;"),n.push("float opacity = color.a;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):n.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&n.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}const Br=h.vec3(),xr=h.vec3(),Pr=h.vec3(),Cr=h.vec3(),Mr=h.mat4();class Fr extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Br;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=xr;if(l){const e=h.transformPoint3(c,l,Pr);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Mr),m=Cr,m[0]=n.eye[0]-t[0],m[1]=n.eye[1]-t[1],m[2]=n.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,m),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElementsInstanced(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Er=h.vec3(),Ir=h.vec3(),Tr=h.vec3(),Dr=h.vec3(),Sr=h.mat4();class Rr extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=Er;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ir;if(l){const e=h.transformPoint3(c,l,Tr);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Sr),m=Dr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ur{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new lr(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ur(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new dr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Fr(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Rr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new nr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new ar(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new ar(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new wr(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new wr(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new wr(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new wr(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new br(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new br(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new lr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new mr(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new gr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new cr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new hr(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ur(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new pr(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new yr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new dr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new fr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new _r(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Rr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Fr(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Lr={};const kr=new Uint8Array(4),Or=new Float32Array(1),Nr=h.vec4([0,0,0,1]),Vr=new Float32Array(3),Qr=h.vec3(),Hr=h.vec3(),Gr=h.vec3(),jr=h.vec3(),zr=h.vec3(),Wr=h.vec3(),Xr=h.vec3(),Kr=new Float32Array(4);class Zr{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Lr[t];return i||(i=new Ur(e),Lr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Lr[t],i._destroy()}))),i}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new ie({numInstances:0,obb:h.OBB3(),origin:h.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=h.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}createPortion(e,t){const i=t.color,s=t.metallic,r=t.roughness,o=null!==t.opacity&&void 0!==t.opacity?t.opacity:255,n=t.meshMatrix,a=t.pickColor;if(this._finalized)throw"Already finalized";const l=i[0],A=i[1],c=i[2];if(this._colors.push(l),this._colors.push(A),this._colors.push(c),this._colors.push(o),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=r?r:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),this._state.geometry.normals){let e=h.transposeMat4(n,h.mat4()),t=h.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]),this._state.numInstances++;const u=this._portions.length,d={};return this.model.scene.readableGeometryEnabled&&(d.matrix=n.slice(),d.inverseMatrix=null,d.normalMatrix=null),this._portions.push(d),this._numPortions++,this.model.numPortions++,this._meshes.push(e),u}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,i=e.textureSet,s=this.model.scene.canvas.gl,r=this._colors.length,o=r/4;if(r>0){let t=!1;e.colorsBuf=new se(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new se(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new se(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new se(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=h.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new se(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new se(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),t.edgeIndices&&t.edgeIndices.length>0&&(e.edgeIndicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new se(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";kr[0]=t[0],kr[1]=t[1],kr[2]=t[2],kr[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(kr,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Gi),r=!!(t&Ki),o=!!(t&Zi),n=!!(t&Ji),a=!!(t&Yi),l=!!(t&zi),A=!!(t&ji);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,h=!s||A?qi.NOT_RENDERED:n?qi.SILHOUETTE_SELECTED:o?qi.SILHOUETTE_HIGHLIGHTED:r?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let u=0;u=!s||A?qi.NOT_RENDERED:n?qi.EDGES_SELECTED:o?qi.EDGES_HIGHLIGHTED:r?qi.EDGES_XRAYED:a?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?qi.PICK:qi.NOT_RENDERED)<<12,d|=(t&Wi?1:0)<<16,Or[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Or,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Vr[0]=t[0],Vr[1]=t[1],Vr[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Vr,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.positionsCompressed,n=this.model.matrix,a=h.vec4();a.set(i.origin,0),a[3]=1,h.mulMat4v4(n,a,a);const l=a[0],A=a[1],c=a[2],u=Nr,d=r.matrix,p=i.positionsDecodeMatrix;for(let e=0,i=o.length;e<i;e+=3)u[0]=o[e],u[1]=o[e+1],u[2]=o[e+2],h.decompressPosition(u,p),h.transformPoint3(d,u,u),u[3]=1,h.mulMat4v4(n,u,u),u[0]+=l,u[1]+=A,u[2]+=c,t(u)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state.geometry;if(!this._portions[e])return void this.model.error("portion not found: "+e);const s=i.indices;for(let e=0,i=s.length;e<i;e++)t(s[e])}setMatrix(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Kr[0]=t[0],Kr[1]=t[4],Kr[2]=t[8],Kr[3]=t[12],this._state.modelMatrixCol0Buf.setData(Kr,i),Kr[0]=t[1],Kr[1]=t[5],Kr[2]=t[9],Kr[3]=t[13],this._state.modelMatrixCol1Buf.setData(Kr,i),Kr[0]=t[2],Kr[1]=t[6],Kr[2]=t[10],Kr[3]=t[14],this._state.modelMatrixCol2Buf.setData(Kr,i)}readGeometryData(e){if(!this._finalized)throw"Not finalized";const t=this._state,i=this.model.matrix,s=t.modelMatrixCol0Buf.getData(e,1),r=t.modelMatrixCol1Buf.getData(e,1),o=t.modelMatrixCol2Buf.getData(e,1),n=[s[0],r[0],o[0],0,s[1],r[1],o[1],0,s[2],r[2],o[2],0,s[3],r[3],o[3],1],a=t.positionsDecodeMatrix,l=h.vec4();l.set(t.origin,0),l[3]=1,h.mulMat4v4(i,l,l);const A=t.indicesBuf.getData(),c=h.mulMat4(n,a,new Array(16));h.mulMat4(i,c,c),c[12]+=l[0],c[13]+=l[1],c[14]+=l[2];const u=t.positionsBuf.getData();return{indices:A,positions:h.transformPositions3(c,u,new Array(u.length))}}drawColorOpaque(e,t){if(this._numCulledLayerPortions===this._numPortions||0===this._numVisibleLayerPortions||this._numTransparentLayerPortions===this._numPortions||this._numXRayedLayerPortions===this._numPortions)return;this._updateBackfaceCull(e,t);const i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,qi.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK))}precisionRayPickSurface(e,t,i,s,r){if(!this.model.scene.readableGeometryEnabled)return!1;const o=this._state.geometry,n=this._state,a=this._portions[e];if(!a)return this.model.error("portion not found: "+e),!1;a.inverseMatrix||(a.inverseMatrix=h.inverseMat4(a.matrix,h.mat4())),r&&!a.normalMatrix&&(a.normalMatrix=h.transposeMat4(a.inverseMatrix,h.mat4()));const l=o.quantizedPositions,A=o.indices,c=n.origin,u=a.offset,d=Qr,p=Hr;d.set(c?h.subVec3(t,c,Gr):t),p.set(i),u&&h.subVec3(d,u),h.transformRay(this.model.worldNormalMatrix,d,p,d,p),h.transformRay(a.inverseMatrix,d,p,d,p);const f=jr,m=zr,g=Wr;let _=!1,v=0;const b=Xr;for(let e=0,i=A.length;e<i;e+=3){const i=3*A[e+0],o=3*A[e+1],y=3*A[e+2];f[0]=l[i],f[1]=l[i+1],f[2]=l[i+2],m[0]=l[o],m[1]=l[o+1],m[2]=l[o+2],g[0]=l[y],g[1]=l[y+1],g[2]=l[y+2];const{positionsDecodeMatrix:w}=n.geometry;if(h.decompressPosition(f,w),h.decompressPosition(m,w),h.decompressPosition(g,w),h.rayTriangleIntersect(d,p,f,m,g,b)){h.transformPoint3(a.matrix,b,b),h.transformPoint3(this.model.worldMatrix,b,b),u&&h.addVec3(b,u),c&&h.addVec3(b,c);const e=Math.abs(h.lenVec3(h.subVec3(b,t,[])));(!_||e>v)&&(v=e,s.set(b),r&&h.triangleNormal(f,m,g,r),_=!0)}}return _&&r&&(h.transformVec3(a.normalMatrix,r,r),h.transformVec3(this.model.worldNormalMatrix,r,r),h.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Jr extends os{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class Yr extends Jr{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class qr extends Jr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const $r=h.vec3(),eo=h.vec3(),to=h.vec3(),io=h.vec3(),so=h.mat4();class ro extends os{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=$r;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=eo;if(l){const e=to;h.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,so),m=io,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const oo=h.vec3(),no=h.vec3(),ao=h.vec3(),lo=h.vec3(),Ao=h.mat4();class co extends os{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=oo;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=no;if(l){const e=ao;h.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Ao),m=lo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ho{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qr(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ro(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new co(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const uo={};class po{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class fo{constructor(e){this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=uo[t];return i||(i=new ho(e),uo[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete uo[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new po(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new ie({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:h.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=h.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=h.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=h.vec3(e.origin)),this.primitive=e.primitive}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=t.positions,s=t.positionsCompressed,r=t.indices,o=t.color,n=t.opacity,a=this._buffer,l=a.positions.length/3;let A;if(h.expandAABB3(this._modelAABB,t.aabb),this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";A=s.length/3;for(let e=0,t=s.length;e<t;e++)a.positions.push(s[e])}else{if(!i)throw"positions expected";A=i.length/3;for(let e=0,t=i.length;e<t;e++)a.positions.push(i[e])}if(o){const e=o[0],t=o[1],i=o[2],s=n;for(let r=0;r<A;r++)a.colors.push(e),a.colors.push(t),a.colors.push(i),a.colors.push(s)}if(r)for(let e=0,t=r.length;e<t;e++)a.indices.push(r[e]+l);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<A;e++)a.offsets.push(0),a.offsets.push(0),a.offsets.push(0);const c=this._portions.length/2;return this._portions.push(l),this._portions.push(A),this._numPortions++,this.model.numPortions++,this._numVerts+=A,this._meshes.push(e),c}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new se(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=js(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new se(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new se(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new se(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new se(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e<r;e+=4)o[e+0]=n,o[e+1]=a,o[e+2]=l,o[e+3]=A;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=2*e,o=this._portions[r],n=this._portions[r+1],a=!!(t&Gi),l=!!(t&Ki),A=!!(t&Zi),c=!!(t&Ji),h=!!(t&zi),u=!!(t&ji);let d,p;d=!a||u||l||A&&!this.model.scene.highlightMaterial.glowThrough||c&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,p=!a||u?qi.NOT_RENDERED:c?qi.SILHOUETTE_SELECTED:A?qi.SILHOUETTE_HIGHLIGHTED:l?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let f=a&&!u&&h?qi.PICK:qi.NOT_RENDERED;const m=t&Wi?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=o,t=o+n;e<t;e++){let t=0;t|=d,t|=p<<4,t|=f<<12,t|=m<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(n);for(let t=0;t<n;t++){let i=0;i|=d,i|=p<<4,i|=f<<12,i|=m<<16,e[t]=i}this._state.flagsBuf.setData(e,o,n)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class mo extends os{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++}}class go extends mo{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class _o extends mo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const vo=h.vec3(),bo=h.vec3(),yo=h.vec3();h.vec3();const wo=h.mat4();class Bo extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=vo;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=bo;if(l){const e=h.transformPoint3(c,l,yo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,wo),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xo=h.vec3(),Po=h.vec3(),Co=h.vec3();h.vec3();const Mo=h.mat4();class Fo extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=xo;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Po;if(l){const e=h.transformPoint3(c,l,Co);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Mo),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Eo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new Bo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Fo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new go(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new _o(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Bo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Fo(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Io={};const To=new Uint8Array(4),Do=new Float32Array(1),So=new Float32Array(3),Ro=new Float32Array(4);class Uo{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Io[t];return i||(i=new Eo(e),Io[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Io[t],i._destroy()}))),i}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new ie({obb:h.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=h.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=h.vec3(e.origin)),this._finalized=!1,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}createPortion(e,t){const i=t.color,s=t.opacity,r=t.meshMatrix;if(this._finalized)throw"Already finalized";const o=i[0],n=i[1],a=i[2];i[3],this._colors.push(o),this._colors.push(n),this._colors.push(a),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(r[0]),this._modelMatrixCol0.push(r[4]),this._modelMatrixCol0.push(r[8]),this._modelMatrixCol0.push(r[12]),this._modelMatrixCol1.push(r[1]),this._modelMatrixCol1.push(r[5]),this._modelMatrixCol1.push(r[9]),this._modelMatrixCol1.push(r[13]),this._modelMatrixCol2.push(r[2]),this._modelMatrixCol2.push(r[6]),this._modelMatrixCol2.push(r[10]),this._modelMatrixCol2.push(r[14]),this._state.numInstances++;const l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),l}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._state,i=t.geometry,s=this._colors.length,r=s/4;if(s>0){let t=!1;this._state.colorsBuf=new se(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new se(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new se(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=h.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new se(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";To[0]=t[0],To[1]=t[1],To[2]=t[2],To[3]=t[3],this._state.colorsBuf.setData(To,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Gi),r=!!(t&Ki),o=!!(t&Zi),n=!!(t&Ji),a=!!(t&Yi),l=!!(t&zi),A=!!(t&ji);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,h=!s||A?qi.NOT_RENDERED:n?qi.SILHOUETTE_SELECTED:o?qi.SILHOUETTE_HIGHLIGHTED:r?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let u=0;u=!s||A?qi.NOT_RENDERED:n?qi.EDGES_SELECTED:o?qi.EDGES_HIGHLIGHTED:r?qi.EDGES_XRAYED:a?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?qi.PICK:qi.NOT_RENDERED)<<12,d|=(t&Wi?1:0)<<16,Do[0]=d,this._state.flagsBuf.setData(Do,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(So[0]=t[0],So[1]=t[1],So[2]=t[2],this._state.offsetsBuf.setData(So,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Ro[0]=t[0],Ro[1]=t[4],Ro[2]=t[8],Ro[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ro,i),Ro[0]=t[1],Ro[1]=t[5],Ro[2]=t[9],Ro[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ro,i),Ro[0]=t[2],Ro[1]=t[6],Ro[2]=t[10],Ro[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ro,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Lo extends os{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class ko extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Oo extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("uniform vec4 color;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push(" float r = dot(cxy, cxy);"),o.push(" if (r > 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class No extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Vo extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Qo extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const Ho=h.vec3(),Go=h.vec3(),jo=h.vec3(),zo=h.vec3(),Wo=h.mat4();class Xo extends os{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=Ho;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Go;if(l){const e=jo;h.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Wo),m=zo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform1f(this._uPointSize,1);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler"),this._uPointSize=e.getLocation("pointSize")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float pointSize;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ko=h.vec3(),Zo=h.vec3(),Jo=h.vec3(),Yo=h.vec3(),qo=h.mat4();class $o extends os{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=Ko;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Zo;if(l){const e=Jo;h.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,qo),m=Yo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class en{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ko(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Oo(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new No(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Qo(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Xo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new $o(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const tn={};class sn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=tn[t];return i||(i=new en(e),tn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete tn[t],i._destroy()}))),i}(e.model.scene);const t=e.maxGeometryBatchSize||5e6,i=function(){const e=[];return{append:function(t,i=1,s=1){e.push({data:t,times:i,denormalizeScale:s})},compileBuffer:function(t){let i=0;e.forEach((e=>{i+=e.times*e.data.length}));const s=new t(i);let r=0;return e.forEach((e=>{const t=e.data,i=e.denormalizeScale,o=s.subarray(r);if(1===i)o.set(t,0);else for(let e=0;e<t.length;++e)o[e]=t[e]*i;let n=t.length;const a=e.times*t.length;for(;n<a;){const e=Math.min(n,a-n);o.set(o.subarray(0,e),n),n+=e}r+=n})),s}}};this._buffer={maxVerts:t,positions:i(),colors:i(),pickColors:i(),vertsIndex:0},this._scratchMemory=e.scratchMemory,this._state=new ie({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:h.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=h.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=h.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=h.vec3(e.origin))}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.vertsIndex+e/3<=this._buffer.maxVerts}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=this._buffer,s=this._preCompressedPositionsExpected?t.positionsCompressed:t.positions;if(!s)throw(this._preCompressedPositionsExpected?"positionsCompressed":"positions")+" expected";i.positions.append(s);const r=s.length/3,o=t.color,n=t.colorsCompressed,a=t.colors,l=t.pickColor;n?i.colors.append(n):a?i.colors.append(a,1,255):o&&i.colors.append([o[0],o[1],o[2],1],r),i.pickColors.append(l.slice(0,4),r),h.expandAABB3(this._modelAABB,t.aabb);const A=this._portions.length/2;return this._portions.push(this._buffer.vertsIndex),this._portions.push(r),this._buffer.vertsIndex+=r,this._numPortions++,this.model.numPortions++,this._meshes.push(e),A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer,s=(e,i,s)=>e.length>0?new se(t,t.ARRAY_BUFFER,e,e.length,i,s):null,r=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):js(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=s(r,3,t.STATIC_DRAW),e.flagsBuf=s(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=s(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=s(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?s(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=4)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=2*e,r=this._portions[s],o=this._portions[s+1],n=this._scratchMemory.getFloat32Array(o),a=!!(t&Gi),l=!!(t&Ki),A=!!(t&Zi),c=!!(t&Ji),h=!!(t&zi),u=!!(t&ji);let d,p;d=!a||u||l||A&&!this.model.scene.highlightMaterial.glowThrough||c&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,p=!a||u?qi.NOT_RENDERED:c?qi.SILHOUETTE_SELECTED:A?qi.SILHOUETTE_HIGHLIGHTED:l?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let f=a&&!u&&h?qi.PICK:qi.NOT_RENDERED;const m=t&Wi?1:0;for(let e=0;e<o;e++){let t=0;t|=d,t|=p<<4,t|=f<<12,t|=m<<16,n[e]=t}this._state.flagsBuf.setData(n,r)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class rn extends os{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,i.positionsBuf.numItems,i.numInstances),r&&s.drawArrays++}}class on extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class nn extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class an extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class ln extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class An extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class cn extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("const float packUpScale = 256. / 255.;"),o.push("const float unpackDownscale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),o.push("const float shiftRight8 = 1.0 / 256.;"),o.push("vec4 packDepthToRGBA( const in float v ) {"),o.push(" vec4 r = vec4( fract( v * packFactors ), v );"),o.push(" r.yzw -= r.xyz * shiftRight8;"),o.push(" return r * packUpScale;"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push(" float r = dot(cxy, cxy);"),o.push(" if (r > 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class hn extends rn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const un=h.vec3(),dn=h.vec3(),pn=h.vec3();h.vec3();const fn=h.mat4();class mn extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=un;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=dn;if(l){const e=h.transformPoint3(c,l,pn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,fn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const gn=h.vec3(),_n=h.vec3(),vn=h.vec3();h.vec3();const bn=h.mat4();class yn extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,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 p=gn;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=_n;if(l){const e=h.transformPoint3(c,l,vn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,bn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class wn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new on(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new nn(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 an(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ln(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new An(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new hn(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new mn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new yn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Bn={};const xn=new Uint8Array(4),Pn=new Float32Array(1),Cn=new Float32Array(3),Mn=new Float32Array(4);class Fn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Bn[t];return i||(i=new wn(e),Bn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Bn[t],i._destroy()}))),i}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new ie({obb:h.OBB3(),numInstances:0,origin:e.origin?h.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=h.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}createPortion(e,t){const i=t.meshMatrix,s=t.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),this._pickColors.push(s[0]),this._pickColors.push(s[1]),this._pickColors.push(s[2]),this._pickColors.push(s[3]),this._state.numInstances++;const r=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),r}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4,i=this._state,s=i.geometry;if(t>0){let s=!1;i.flagsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new se(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=h.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new se(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new se(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";xn[0]=t[0],xn[1]=t[1],xn[2]=t[2],this._state.colorsBuf.setData(xn,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Gi),r=!!(t&Ki),o=!!(t&Zi),n=!!(t&Ji),a=!!(t&Yi),l=!!(t&zi),A=!!(t&ji);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,h=!s||A?qi.NOT_RENDERED:n?qi.SILHOUETTE_SELECTED:o?qi.SILHOUETTE_HIGHLIGHTED:r?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let u=0;u=!s||A?qi.NOT_RENDERED:n?qi.EDGES_SELECTED:o?qi.EDGES_HIGHLIGHTED:r?qi.EDGES_XRAYED:a?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?qi.PICK:qi.NOT_RENDERED)<<12,d|=(t&Wi?255:0)<<16,Pn[0]=d,this._state.flagsBuf.setData(Pn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Cn[0]=t[0],Cn[1]=t[1],Cn[2]=t[2],this._state.offsetsBuf.setData(Cn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Mn[0]=t[0],Mn[1]=t[4],Mn[2]=t[8],Mn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Mn,i),Mn[0]=t[1],Mn[1]=t[5],Mn[2]=t[9],Mn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Mn,i),Mn[0]=t[2],Mn[1]=t[6],Mn[2]=t[10],Mn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Mn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const En=h.vec3(),In=h.vec3(),Tn=h.mat4();class Dn{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=En;if(f){const t=h.transformPoint3(u,A,In);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,Tn)}else p=d;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,En,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uPerObjectDecodeMatrix="uPerObjectDecodeMatrix",this.uPerObjectColorAndFlags="uPerObjectColorAndFlags",this._uPerVertexPosition="uPerVertexPosition",this._uPerLineIndices="uPerLineIndices",this._uPerLineObject="uPerLineObject",this._uPerObjectMatrix="uPerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Sn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Dn(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Rn={};class Un{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Ln{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class kn{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const On={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(On,null,4));let e=0;Object.keys(On).forEach((t=>{t.startsWith("size")&&(e+=On[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/On.totalLines).toFixed(2)}`);let t={};Object.keys(On).forEach((i=>{i.startsWith("size")&&(t[i]=`${(On[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Nn{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);On.sizeDataColorsAndFlags+=l.byteLength,On.numberOfTextures++;for(let e=0;e<o;e++)l.set(t[e],32*e+0),l.set(i[e],32*e+4),l.set([0,0,0,0],32*e+8),l.set([0,0,0,0],32*e+12),l.set([s[e]>>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);On.sizeDataTextureOffsets+=r.byteLength,On.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);On.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r,o)}generateTextureForPositionsDecodeMatrices(e,t){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);On.sizeDataPositionDecodeMatrices+=o.byteLength,On.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureFor8BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*3);On.sizeDataTextureIndices+=o.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureFor16BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*3);On.sizeDataTextureIndices+=o.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureFor32BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*3);On.sizeDataTextureIndices+=o.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureForPositions(e,t,i){const s=i/3,r=4096,o=Math.ceil(s/r);if(0===o)throw"texture height===0";const n=new Uint16Array(r*o*3);On.sizeDataTexturePositions+=n.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];n.set(s,i),i+=s.length}const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,o),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,o,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,a,r,o)}generateTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const i=t.length,s=4096,r=Math.ceil(i/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r);o.set(t,0),On.sizeDataTexturePortionIds+=o.byteLength,On.numberOfTextures++;const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}}const Vn=new Ns,Qn=Vn.maxDataTextureHeight,Hn=new Float32Array(16),Gn=new Uint8Array(4),jn=new Float32Array(3);let zn=0;const Wn=h.identityMat4();class Xn{constructor(e,t){On.numberOfLayers++,this._layerNumber=zn++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._renderers=function(e){const t=e.id;let i=Rn[t];return i||(i=new Sn(e),Rn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Rn[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Un,this._dataTextureState=new Ln,this._dataTextureGenerator=new Nn,this._state=new ie({origin:h.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&On.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*Qn||t+r>4096*Qn)&&On.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Qn&&t+r<=4096*Qn}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;On.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,On.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||Wn),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,On.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,On.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,On.totalLines32Bits+=t.numLines),On.totalLines+=t.numLines;for(let i=0;i<t.numLines;i+=8)e.push(A)}return this._subPortions.push({numVertices:t.numLines}),this._numPortions++,On.numberOfPortions++,A}finalize(){if(this._finalized)return;const e=this._state,t=this._dataTextureState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dataTextureGenerator.generateTextureForInstancingMatrices(i,s.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(i,s.positionsCompressed,s.lenPositionsCompressed),t.texturePerLineIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId8Bits),t.texturePerLineIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId16Bits),t.texturePerLineIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId32Bits),s.lenIndices8Bits>0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetColor(i[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;Gn[0]=t[0],Gn[1]=t[1],Gn[2]=t[2],Gn[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(Gn,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Gn))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e<o;e++)this._subPortionSetFlags(r[e],t,i,s)}_subPortionSetFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=!!(t&Gi),o=!!(t&Ki),n=!!(t&ji);let a,l;a=!r||n||o?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,l=!r||n?qi.NOT_RENDERED:!!(t&Ji)?qi.SILHOUETTE_SELECTED:!!(t&Zi)?qi.SILHOUETTE_HIGHLIGHTED:o?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let A=r&&!n&&!!(t&zi)?qi.PICK:qi.NOT_RENDERED;const c=this._dataTextureState,h=this.model.scene.canvas.gl;Gn[0]=a,Gn[1]=l,Gn[3]=A,c.texturePerObjectColorsAndFlags._textureData.set(Gn,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),h.bindTexture(h.TEXTURE_2D,c.texturePerObjectColorsAndFlags._texture),h.texSubImage2D(h.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,h.RGBA_INTEGER,h.UNSIGNED_BYTE,Gn))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e<r;e++)this._subPortionSetFlags2(s[e],t,i)}_subPortionSetFlags2(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=t&Wi?255:0,r=this._dataTextureState,o=this.model.scene.canvas.gl;Gn[0]=s,Gn[1]=0,Gn[2]=1,Gn[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(Gn,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Gn))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetOffset(i[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;jn[0]=t[0],jn[1]=t[1],jn[2]=t[2],i.texturePerObjectOffsets._textureData.set(jn,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,jn))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetMatrix(i[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;Hn.set(t),i.texturePerObjectInstanceMatrices._textureData.set(Hn,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Hn))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const Kn=h.vec3(),Zn=h.vec3(),Jn=h.vec3();h.vec3();const Yn=h.vec4(),qn=h.mat4();class $n{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=Kn;if(f){const t=h.transformPoint3(u,A,Zn);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=He(r.viewMatrix,e,qn),p=Jn,p[0]=r.eye[0]-e[0],p[1]=r.eye[1]-e[1],p[2]=r.eye[2]-e[2]}else d=r.viewMatrix,p=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,p),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;s.crossSections&&(n.uniform4fv(this._uSliceColor,s.crossSections.sliceColor),n.uniform1f(this._uSliceThickness,s.crossSections.sliceThickness));for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Kn,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new it(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}this._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),e.crossSections&&(this._uSliceColor=s.getLocation("sliceColor"),this._uSliceThickness=s.getLocation("sliceThickness"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState.lights,o=t.camera.project;s.bind(),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=r.length;e<t;e++){const t=r[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const s=t.sao;if(s.possible){const t=i.drawingBufferWidth,r=i.drawingBufferHeight;Yn[0]=t,Yn[1]=r,Yn[2]=s.blendCutoff,Yn[3]=s.blendFactor,i.uniform4fv(this._uSAOParams,Yn),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++)r=i.lights[e],"ambient"!==r.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===r.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")));s&&(o.push("out vec4 vWorldPosition;"),o.push("flat out uint vFlags2;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int polygonIndex = gl_VertexID / 3;"),o.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e<t;e++)if(r=i.lights[e],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?o.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return o.push("vec3 rgb = vec3(color.rgb) / 255.0;"),o.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags2 = flags2.r;")),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(s.push(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ea=new Float32Array([1,1,1]),ta=h.vec3(),ia=h.vec3(),sa=h.vec3();h.vec3();const ra=h.mat4();class oa{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const e=ta;if(A){const t=ia;h.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,ra),f=sa,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=d,f=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===qi.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,ea);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),g=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*g,r=o.renderFlags;for(let t=0;t<m;t++){const s=this._uSectionPlanes[t];if(s)if(t<g){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ta,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("uniform vec4 color;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = color;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const na=new Float32Array([0,0,0,1]),aa=h.vec3(),la=h.vec3();h.vec3();const Aa=h.mat4();class ca{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=aa;if(f){const t=h.transformPoint3(u,A,la);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,Aa)}else p=d;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===qi.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,na);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,aa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ha=h.vec3(),ua=h.vec3(),da=h.mat4();class pa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=ha;if(f){const t=h.transformPoint3(u,A,ua);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,da)}else p=d;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ha,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const fa=h.vec3(),ma=h.vec3(),ga=h.vec3(),_a=h.mat4();class va{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=e.pickViewMatrix||o.viewMatrix,p=e.pickProjMatrix||o.projMatrix,f=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let g,_;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==c[0]||0!==c[1]||0!==c[2];if(v||b){const e=fa;if(v){const t=h.transformPoint3(u,A,ma);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],g=He(d,e,_a),_=ga,_[0]=f[0]-e[0],_[1]=f[1]-e[1],_[2]=f[2]-e[2]}else g=d,_=f;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),w=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*w,o=s.renderFlags;for(let t=0;t<y;t++){const r=this._uSectionPlanes[t];if(r)if(t<w){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,fa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("in vec4 vPickColor;"),i.push("out vec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ba=h.vec3(),ya=h.vec3(),wa=h.vec3();h.vec3();const Ba=h.mat4();class xa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=e.pickViewMatrix||o.viewMatrix,p=e.pickProjMatrix||o.projMatrix,f=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let g,_;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const t=ba;if(A){const e=ya;h.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],g=He(d,t,Ba),_=wa,_[0]=f[0]-t[0],_[1]=f[1]-t[1],_[2]=f[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=d,_=f,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const v=r._sectionPlanesState.getNumAllocatedSectionPlanes(),b=r._sectionPlanesState.sectionPlanes.length;if(v>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*b,o=s.renderFlags;for(let t=0;t<v;t++){const r=this._uSectionPlanes[t];if(r)if(t<b){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ba,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 packDepth(const in float depth) {"),i.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),i.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),i.push(" vec4 res = fract(depth * bitShift);"),i.push(" res -= res.xxyz * bitMask;"),i.push(" return res;"),i.push("}"),i.push("out vec4 outPackedDepth;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Pa=h.vec3(),Ca=h.vec3(),Ma=h.vec3(),Fa=h.vec3();h.vec3();const Ea=h.mat4();class Ia{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix,f=Pa;let m,g;f[0]=h.safeInv(d[3]-d[0])*h.MAX_INT,f[1]=h.safeInv(d[4]-d[1])*h.MAX_INT,f[2]=h.safeInv(d[5]-d[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const _=0!==A[0]||0!==A[1]||0!==A[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(_||v){const t=Ca;if(_){const e=h.transformPoint3(u,A,Ma);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],m=He(p,t,Ea),g=Fa,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t<b;t++){const r=this._uSectionPlanes[t];if(r)if(t<y){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Pa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}const w="edge"===e.snapMode?n.LINES:n.POINTS;a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(w,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(w,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(w,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this.uVectorA=i.getLocation("uSnapVectorA"),this.uInverseVectorAB=i.getLocation("uSnapInvVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ta=h.vec3(),Da=h.vec3(),Sa=h.vec3(),Ra=h.vec3();h.vec3();const Ua=h.mat4();class La{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix,f=Ta;let m,g;f[0]=h.safeInv(d[3]-d[0])*h.MAX_INT,f[1]=h.safeInv(d[4]-d[1])*h.MAX_INT,f[2]=h.safeInv(d[5]-d[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const _=0!==A[0]||0!==A[1]||0!==A[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(_||v){const t=Da;if(_){const e=Sa;h.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],m=He(p,t,Ua),g=Ra,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t<b;t++){const r=this._uSectionPlanes[t];if(r)if(t<y){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Ta,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this._uVectorA=i.getLocation("uVectorAB"),this._uInverseVectorAB=i.getLocation("uInverseVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ka=h.vec3(),Oa=h.vec3(),Na=h.vec3();h.vec3();const Va=h.mat4();class Qa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const e=ka;if(A){const t=Oa;h.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,Va),f=Na,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),g=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*g,o=s.renderFlags;for(let t=0;t<m;t++){const r=this._uSectionPlanes[t];if(r)if(t<g){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ka,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(){const e=this._scene;e.canvas.gl,e.camera.project,this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push(" if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ha=h.vec3(),Ga=h.vec3(),ja=h.vec3();h.vec3();const za=h.mat4();class Wa{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=Ha;if(f){const t=h.transformPoint3(u,A,Ga);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=He(r.viewMatrix,e,za),p=ja,p[0]=r.eye[0]-e[0],p[1]=r.eye[1]-e[1],p[2]=r.eye[2]-e[2]}else d=r.viewMatrix,p=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,p),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Ha,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xa=h.vec3(),Ka=h.vec3(),Za=h.vec3();h.vec3();const Ja=h.mat4();class Ya{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const f=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(f||m){const e=Xa;if(f){const t=Ka;h.transformPoint3(c,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],d=He(u,e,Ja),p=Za,p[0]=o.eye[0]-e[0],p[1]=o.eye[1]-e[1],p[2]=o.eye[2]-e[2]}else d=u,p=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(l){const e=ze(i.dist,i.dir,l,Xa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.objectDecodeAndInstanceMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2&&(this._aFlags2=i.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(st.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t<e._sectionPlanesState.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in vec3 vViewNormal;"),i.push("vec3 packNormalToRGB( const in vec3 normal ) {"),i.push(" return normalize( normal ) * 0.5 + 0.5;"),i.push("}"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qa=h.vec3(),$a=h.vec3(),el=h.vec3();h.vec3(),h.vec4();const tl=h.mat4();class il{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));const d=e.pickViewMatrix||r.viewMatrix,p=e.pickProjMatrix||r.projMatrix,f=e.pickOrigin||r.eye,m=e.pickProjMatrix?e.pickZFar:r.project.far;let g,_;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==c[0]||0!==c[1]||0!==c[2];if(v||b){const e=qa;if(v){const t=h.transformPoint3(u,A,$a);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],g=He(d,e,tl),_=el,_[0]=f[0]-e[0],_[1]=f[1]-e[1],_[2]=f[2]-e[2]}else g=d,_=f;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),w=s._sectionPlanesState.sectionPlanes.length;if(y>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*w,r=o.renderFlags;for(let t=0;t<y;t++){const s=this._uSectionPlanes[t];if(s)if(t<w){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,qa,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out highp ivec4 outNormal;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class sl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new oa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new va(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new xa(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new il(this._scene)),this._snapRenderer||(this._snapRenderer=new Ia(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new La(this._scene)),this._snapRenderer||(this._snapRenderer=new Ia(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new $n(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new $n(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new oa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Wa(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ya(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new ca(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new pa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new va(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new il(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new il(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new xa(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ia(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new La(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Qa(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const rl={};class ol{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class nl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const al={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(al,null,4));let e=0;Object.keys(al).forEach((t=>{t.startsWith("size")&&(e+=al[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/al.totalPolygons).toFixed(2)}`);let t={};Object.keys(al).forEach((i=>{i.startsWith("size")&&(t[i]=`${(al[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class ll{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const c=new Uint8Array(16384*A);al.sizeDataColorsAndFlags+=c.byteLength,al.numberOfTextures++;for(let e=0;e<a;e++)c.set(t[e],32*e+0),c.set(i[e],32*e+4),c.set([0,0,0,0],32*e+8),c.set([0,0,0,0],32*e+12),c.set([s[e]>>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),c.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),c.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),c.set([n[e]?1:0,0,0,0],32*e+28);const h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,h,l,A,c)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);al.sizeDataTextureOffsets+=r.byteLength,al.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);al.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r,o)}createTextureForPositionsDecodeMatrices(e,t){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);al.sizeDataPositionDecodeMatrices+=o.byteLength,al.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor8BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*3);al.sizeDataTextureIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor16BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*3);al.sizeDataTextureIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor32BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*3);al.sizeDataTextureIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor8BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*2);al.sizeDataTextureEdgeIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor16BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*2);al.sizeDataTextureEdgeIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor32BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*2);al.sizeDataTextureEdgeIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureForPositions(e,t,i){const s=i/3,r=4096,o=Math.ceil(s/r);if(0===o)throw"texture height===0";const n=new Uint16Array(r*o*3);al.sizeDataTexturePositions+=n.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];n.set(s,i),i+=s.length}const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,o),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,o,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,a,r,o)}createTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const i=t.length,s=4096,r=Math.ceil(i/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r);o.set(t,0),al.sizeDataTexturePortionIds+=o.byteLength,al.numberOfTextures++;const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}}const Al=new Ns,cl=Al.maxDataTextureHeight,hl=h.vec4(),ul=new Float32Array(16),dl=new Uint8Array(4),pl=new Float32Array(3);let fl=0;const ml=h.identityMat4();class gl{constructor(e,t){al.numberOfLayers++,this._layerNumber=fl++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._renderers=function(e){const t=e.id;let i=rl[t];return i||(i=new sl(e),rl[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete rl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new ol,this._dtxState=new nl,this._dtxTextureFactory=new ll,this._state=new ie({origin:h.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e<t;e++)h.expandAABB3(this._aabb,this._meshes[e].aabb);this.aabbDirty=!1}return this._aabb}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&al.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*cl||t+r>4096*cl)&&al.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*cl&&t+r<=4096*cl}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;al.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;al.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,c=0;if(s){let e;c=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let h=0;if(r){let e;h=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,al.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:c,numEdges:h,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,c=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||ml),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?c.numIndices8Bits:t.numVertices<=65536?c.numIndices16Bits:c.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?c.numEdgeIndices8Bits:t.numVertices<=65536?c.numEdgeIndices16Bits:c.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const h=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,c.numIndices8Bits+=i,al.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,c.numIndices16Bits+=i,al.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,c.numIndices32Bits+=i,al.totalPolygons32Bits+=t.numTriangles),al.totalPolygons+=t.numTriangles;for(let i=0;i<t.numTriangles;i+=8)e.push(h)}if(t.numEdges>0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,c.numEdgeIndices8Bits+=i,al.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,c.numEdgeIndices16Bits+=i,al.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,c.numEdgeIndices32Bits+=i,al.totalEdges32Bits+=t.numEdges),al.totalEdges+=t.numEdges;for(let i=0;i<t.numEdges;i+=8)e.push(h)}return this._subPortions.push({numVertices:t.numTriangles}),this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries[h]={indices:i.indices,positionsCompressed:i.positionsCompressed,positionsDecodeMatrix:e.positionsDecodeMatrix,meshMatrix:e.meshMatrix}),this._numPortions++,al.numberOfPortions++,h}finalize(){if(this._finalized)return;const e=this._state,t=this._dtxState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectColorsAndFlags=this._dtxTextureFactory.createTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectEdgeIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dtxTextureFactory.createTextureForInstancingMatrices(i,s.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dtxTextureFactory.createTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dtxTextureFactory.createTextureForPositions(i,s.positionsCompressed,s.lenPositionsCompressed),t.texturePerPolygonIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId8Bits),t.texturePerPolygonIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId16Bits),t.texturePerPolygonIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId32Bits),s.perEdgeNumberPortionId8Bits.length>0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetColor(i[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;dl[0]=t[0],dl[1]=t[1],dl[2]=t[2],dl[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(dl,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,dl))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e<o;e++)this._subPortionSetFlags(r[e],t,i,s)}_subPortionSetFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=!!(t&Gi),o=!!(t&Ki),n=!!(t&Zi),a=!!(t&Ji),l=!!(t&Yi),A=!!(t&zi),c=!!(t&ji);let h,u;h=!r||c||o||n&&!this.model.scene.highlightMaterial.glowThrough||a&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,u=!r||c?qi.NOT_RENDERED:a?qi.SILHOUETTE_SELECTED:n?qi.SILHOUETTE_HIGHLIGHTED:o?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let d=0;d=!r||c?qi.NOT_RENDERED:a?qi.EDGES_SELECTED:n?qi.EDGES_HIGHLIGHTED:o?qi.EDGES_XRAYED:l?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let p=r&&!c&&A?qi.PICK:qi.NOT_RENDERED;const f=this._dtxState,m=this.model.scene.canvas.gl;dl[0]=h,dl[1]=u,dl[2]=d,dl[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(dl,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),m.bindTexture(m.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),m.texSubImage2D(m.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,m.RGBA_INTEGER,m.UNSIGNED_BYTE,dl))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e<r;e++)this._subPortionSetFlags2(s[e],t,i)}_subPortionSetFlags2(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=t&Wi?255:0,r=this._dtxState,o=this.model.scene.canvas.gl;dl[0]=s,dl[1]=0,dl[2]=1,dl[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(dl,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,dl))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetOffset(i[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;pl[0]=t[0],pl[1]=t[1],pl[2]=t[2],i.texturePerObjectOffsets._textureData.set(pl,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,pl))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetMatrix(i[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;ul.set(t),i.texturePerObjectInstanceMatrices._textureData.set(ul,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,ul))}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portionToSubPortionsMap[e];if(s)for(let e=0,r=s.length;e<r;e++){const r=s[e],o=this._subPortionReadableGeometries[r],n=o.positionsCompressed,a=o.positionsDecodeMatrix;o.meshMatrix;const l=i.origin,A=l[0],c=l[1],u=l[2],d=hl;for(let e=0,i=n.length;e<i;e+=3)d[0]=n[e],d[1]=n[e+1],d[2]=n[e+2],d[3]=1,h.decompressPosition(d,a),h.mulMat4v4(this.model.worldMatrix,d,d),d[0]+=A,d[1]+=c,d[2]+=u,t(d)}else this.model.error("portion not found: "+e)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._portionToSubPortionsMap[e];if(i)for(let e=0,s=i.length;e<s;e++){const s=i[e],r=this._subPortionReadableGeometries[s].indices;for(let e=0,i=r.length;e<i;e++)t(r[e])}else this.model.error("portion not found: "+e)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,qi.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class _l{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.alphaCutoff=e.alphaCutoff,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class vl{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const bl={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class yl{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t<i;t+=2){const i=this.handlers[t],s=this.handlers[t+1];if(i.global&&(i.lastIndex=0),i.test(e))return s}return null}}const wl=new yl;class Bl{constructor(e){this.manager=void 0!==e?e:wl,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const i=this;return new Promise((function(s,r){i.load(e,s,t,r)}))}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}const xl={};class Pl extends Bl{constructor(e){super(e)}load(e,t,i,s){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=bl.get(e);if(void 0!==r)return this.manager.itemStart(e),M.scheduleTask((()=>{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==xl[e])return void xl[e].push({onLoad:t,onProgress:i,onError:s});xl[e]=[],xl[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=xl[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e<t;e++){const t=i[e];t.onProgress&&t.onProgress(s)}e.enqueue(r),t()}}))}()}});return new Response(l)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{bl.add(e,t);const i=xl[e];delete xl[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onLoad&&s.onLoad(t)}})).catch((t=>{const i=xl[e];if(void 0===i)throw this.manager.itemError(e),t;delete xl[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onError&&s.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Cl{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:t,msg:i,transfer:s}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(i,s)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((i=>{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=i,this.workers[s].postMessage(e,t)):this.queue.push({resolve:i,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Ml=0;class Fl{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Cl,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Pl;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new Pl;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=Fl.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(Fl.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Fl.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Fl.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),Ml>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Ml++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:c,dfdTransferFn:h,dfdFlags:u}=i;if("error"===A)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Ml--}}Fl.BasisFormat={ETC1S:0,UASTC_4x4:1},Fl.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},Fl.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},Fl.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,h=c.transcoderBinary,t=new Promise((e=>{i={wasmBinary:h,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),g=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,c){let h,u;const d=t===o.ETC1S?a:l;for(let s=0;s<d.length;s++){const r=d[s];if(e[r.if]&&(r.basisFormat.includes(t)&&!(c&&r.transcoderFormat.length<2)&&(!r.needsPowerOfTwo||A(i)&&A(n))))return h=r.transcoderFormat[c?1:0],u=r.engineFormat[c?1:0],{transcoderFormat:h,engineFormat:u}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=r.RGBA32,u=s.RGBAFormat,{transcoderFormat:h,engineFormat:u}}(h,u,d,f);if(!u||!d||!p)throw c(),new Error("KTX2TextureTranscoder: Invalid texture");if(!n.startTranscoding())throw c(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const b=[];for(let e=0;e<p;e++){const t=n.getImageLevelInfo(e,0,0),i=t.origWidth,s=t.origHeight,r=new Uint8Array(n.getImageTranscodedSizeInBytes(e,0,0,_));if(!n.transcodeImage(r,e,0,0,_,0,-1,-1))throw c(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");b.push({data:r,width:i,height:s})}return c(),{width:u,height:d,hasAlpha:f,mipmaps:b,format:v,dfdTransferFn:m,dfdFlags:g}}(c.buffers[0]),m=[];for(let e=0;e<u.length;++e)m.push(u[e].data.buffer);self.postMessage({type:"transcode",id:c.id,width:t,height:n,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f},m)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:c.id,error:e.message})}}))}var h}));const n=[{if:"astcSupported",basisFormat:[o.UASTC_4x4],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[s.RGBA_ASTC_4x4_Format,s.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[s.RGBA_BPTC_Format,s.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.BC1,r.BC3],engineFormat:[s.RGB_S3TC_DXT1_Format,s.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[s.RGB_ETC2_Format,s.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.ETC1],engineFormat:[s.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[s.RGB_PVRTC_4BPPV1_Format,s.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],a=n.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),l=n.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function A(e){return e<=2||0==(e&e-1)&&0!==e}};const El={};function Il(e){const t=e.scene.id;let i=El[t];return i||(i=new Fl({viewer:e}),El[t]=i,e.scene.on("destroyed",(()=>{delete El[t],i.destroy()}))),i}