function xmlToJson(e,t){if(e.nodeType===e.TEXT_NODE){var i=e.nodeValue;if(null===i.match(/^\s+$/))return i}else if(e.nodeType===e.ELEMENT_NODE||e.nodeType===e.DOCUMENT_NODE){var s={type:e.nodeName,children:[]};if(e.nodeType===e.ELEMENT_NODE)for(var r=0;r<e.attributes.length;r++){var o=e.attributes[r];s[t[o.nodeName]||o.nodeName]=o.nodeValue}for(var a=0;a<e.childNodes.length;a++){(r=xmlToJson(e.childNodes[a],t))&&s.children.push(r)}return s}}function clone(e){return JSON.parse(JSON.stringify(e))}var guidChars=[["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 b64(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map(function(t){return guidChars.substr(parseInt(e/(1<<t))%64,1)}).reverse().join("")}function compressGuid(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 b64(t[0],2)+[1,4,7,10,13].map(function(e){return b64((t[e]<<16)+(t[e+1]<<8)+t[e+2])}).join("")}function findNodeOfType(e,t){var i=[],s=function(e){e.type===t&&i.push(e),(e.children||[]).forEach(function(e){s(e)})};return s(e),i}function timeout(e){return new Promise(function(t,i){setTimeout(t,e)})}function httpRequest(e){return new Promise(function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(r){console.log(e.url,s.readyState,s.status),4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)})}const queryString=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}();function loadJSON(e,t,i){var s=e=>void 0;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)}function loadArraybuffer(e,t,i){var s=e=>void 0;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),s=new Uint8Array(e);for(var a=0;a<o.length;a++)s[a]=o.charCodeAt(a);window.setTimeout(function(){t(e)},0)}catch(e){window.setTimeout(function(){i(e)},0)}}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)}}function isArray(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length}function isString(e){return"string"==typeof e||e instanceof String}function isNumeric(e){return!isNaN(parseFloat(e))&&isFinite(e)}function isID(e){return utils.isString(e)||utils.isNumeric(e)}function isSameComponent(e,t){if(!e||!t)return!1;return(utils.isNumeric(e)||utils.isString(e)?`${e}`:e.id)===(utils.isNumeric(t)||utils.isString(t)?`${t}`:t.id)}function isFunction(e){return"function"==typeof e}function isObject(e){const t={}.constructor;return!!e&&e.constructor===t}function copy(e){return utils.apply(e,{})}function apply(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}function apply2(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t}function applyIf(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t}function isEmptyObject(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function inQuotes(e){return utils.isNumeric(e)?`${e}`:`'${e}'`}function concat(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i}function flattenParentChildHierarchy(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}const utils={xmlToJson:xmlToJson,clone:clone,compressGuid:compressGuid,findNodeOfType:findNodeOfType,timeout:timeout,httpRequest:httpRequest,loadJSON:loadJSON,loadArraybuffer:loadArraybuffer,queryString:queryString,isArray:isArray,isString:isString,isNumeric:isNumeric,isID:isID,isSameComponent:isSameComponent,isFunction:isFunction,isObject:isObject,copy:copy,apply:apply,apply2:apply2,applyIf:applyIf,isEmptyObject:isEmptyObject,inQuotes:inQuotes,concat:concat,flattenParentChildHierarchy:flattenParentChildHierarchy};class Server{constructor(e={}){this._dataDir=e.dataDir||""}getProjects(e,t){const i=this._dataDir+"/projects/index.json";utils.loadJSON(i,e,t)}getProject(e,t,i){const s=this._dataDir+"/projects/"+e+"/index.json";utils.loadJSON(s,t,i)}getMetadata(e,t,i,s){const r=this._dataDir+"/projects/"+e+"/models/"+t+"/metadata.json";utils.loadJSON(r,i,s)}getGeometry(e,t,i,s){const r=this._dataDir+"/projects/"+e+"/models/"+t+"/geometry.xkt";utils.loadArraybuffer(r,i,s)}getObjectInfo(e,t,i,s,r){const o=this._dataDir+"/projects/"+e+"/models/"+t+"/objects/"+i+"/properties.json";utils.loadJSON(o,s,r)}getIssues(e,t,i,s){const r=this._dataDir+"/projects/"+e+"/models/"+t+"/issues.json";utils.loadJSON(r,i,s)}}class Map{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}}class Controller{constructor(e,t,i,s){this.bimViewer=e?e.bimViewer||e:this,this.server=e?e.server:i,this.viewer=e?e.viewer:s,this._children=[],e&&e._children.push(this),this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._enabled=null,this._active=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];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(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Map),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[e];s||(s={},this._eventSubs[e]=s);const r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;const o=this._events[e];return void 0!==o&&t.call(i||this,o),r}off(e){if(void 0===e||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._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)}log(e){e="[LOG] "+e,window.console.log(e)}warn(e){e="[WARN] "+e,window.console.warn(e)}error(e){e="[ERROR] "+e,window.console.error(e)}_mutexActivation(e){const t=e.length;for(let i=0;i<t;i++){e[i].on("active",function(){const s=i;return function(i){if(i)for(let i=0;i<t;i++)i!==s&&e[i].setActive(!1)}}())}}setEnabled(e){this._enabled!==e&&(this._enabled=e,this.fire("enabled",this._enabled))}getEnabled(){return this._enabled}setActive(e){this._active!==e&&(this._active=e,this.fire("active",this._active))}getActive(){return this._active}destroy(){if(!this.destroyed){this.fire("destroyed",this.destroyed=!0),this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0;for(let e=0,t=this._children.length;e<t;e++)this._children.destroy();this._children=[]}}}class BusyModal extends Controller{constructor(e,t={}){super(e,t);const i=t.busyModalBackdropElement||document.body;if(!i)throw"Missing config: busyModalBackdropElement";this._modal=document.createElement("div"),this._modal.classList.add("xeokit-busy-modal"),this._modal.innerHTML='<div class="xeokit-busy-modal-content"><div class="xeokit-busy-modal-body"><div class="xeokit-busy-modal-message">Default text</div></div></div>',i.appendChild(this._modal),this._modalVisible=!1,this._modal.style.display="hidden"}show(e){this._modalVisible=!0,this._modal.querySelector(".xeokit-busy-modal-message").innerText=e,this._modal.style.display="block"}hide(){this._modalVisible=!1,this._modal.style.display="none"}destroy(){super.destroy(),this._modal&&(this._modal.parentNode.removeChild(this._modal),this._modal=null)}}const tempMat1=new Float32Array(16),tempMat2=new Float32Array(16),tempVec4=new Float32Array(4),math={MAX_DOUBLE:Number.MAX_VALUE,MIN_DOUBLE:Number.MIN_VALUE,DEGTORAD:.0174532925,RADTODEG:57.295779513,vec2:e=>new Float32Array(e||2),vec3:e=>new Float32Array(e||3),vec4:e=>new Float32Array(e||4),mat3:e=>new Float32Array(e||9),mat3ToMat4:(e,t=new Float32Array(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 Float32Array(e||16),mat4ToMat3(e,t){},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},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),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],a=t[1],n=t[2];return[s*n-r*a,r*o-i*n,i*a-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],a=t[0],n=t[1],l=t[2];return i[0]=r*l-o*n,i[1]=o*a-s*l,i[2]=s*n-r*a,i},sqLenVec4:e=>math.dotVec4(e,e),lenVec4:e=>Math.sqrt(math.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=>math.dotVec3(e,e),sqLenVec2:e=>math.dotVec2(e,e),lenVec3:e=>Math.sqrt(math.sqLenVec3(e)),distVec3:(()=>{const e=new Float32Array(3);return(t,i)=>math.lenVec3(math.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(math.sqLenVec2(e)),distVec2:(()=>{const e=new Float32Array(2);return(t,i)=>math.lenVec2(math.subVec2(t,i,e))})(),rcpVec3:(e,t)=>math.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/math.lenVec4(e);return math.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/math.lenVec3(e);return math.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/math.lenVec2(e);return math.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=math.dotVec3(e,t)/Math.sqrt(math.sqLenVec3(e)*math.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new Float32Array(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=math.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=math.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=math.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||new Float32Array(3))[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:()=>math.m4s(0),setMat4ToOnes:()=>math.m4s(1),diagonalMat4v:e=>new Float32Array([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)=>math.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>math.diagonalMat4c(e,e,e,e),identityMat4:(e=new Float32Array(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 Float32Array(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)=>math.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],a=e[3],n=e[4],l=e[5],h=e[6],c=e[7],d=e[8],u=e[9],p=e[10],m=e[11],_=e[12],g=e[13],f=e[14],v=e[15],b=t[0],y=t[1],M=t[2],w=t[3],x=t[4],P=t[5],E=t[6],A=t[7],C=t[8],S=t[9],R=t[10],L=t[11],D=t[12],k=t[13],T=t[14],I=t[15];return i[0]=b*s+y*n+M*d+w*_,i[1]=b*r+y*l+M*u+w*g,i[2]=b*o+y*h+M*p+w*f,i[3]=b*a+y*c+M*m+w*v,i[4]=x*s+P*n+E*d+A*_,i[5]=x*r+P*l+E*u+A*g,i[6]=x*o+P*h+E*p+A*f,i[7]=x*a+P*c+E*m+A*v,i[8]=C*s+S*n+R*d+L*_,i[9]=C*r+S*l+R*u+L*g,i[10]=C*o+S*h+R*p+L*f,i[11]=C*a+S*c+R*m+L*v,i[12]=D*s+k*n+T*d+I*_,i[13]=D*r+k*l+T*u+I*g,i[14]=D*o+k*h+T*p+I*f,i[15]=D*a+k*c+T*m+I*v,i},mulMat3(e,t,i){i||(i=new Float32Array(9));const s=e[0],r=e[3],o=e[6],a=e[1],n=e[4],l=e[7],h=e[2],c=e[5],d=e[8],u=t[0],p=t[3],m=t[6],_=t[1],g=t[4],f=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*u+r*_+o*v,i[3]=s*p+r*g+o*b,i[6]=s*m+r*f+o*y,i[1]=a*u+n*_+l*v,i[4]=a*p+n*g+l*b,i[7]=a*m+n*f+l*y,i[2]=h*u+c*_+d*v,i[5]=h*p+c*g+d*b,i[8]=h*m+c*f+d*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=math.vec4()){const s=t[0],r=t[1],o=t[2],a=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*a,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*a,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*a,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*a,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],a=e[12],n=e[9];if(!t||e===t){const t=e[1],l=e[2],h=e[3],c=e[6],d=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=a,e[4]=t,e[6]=n,e[7]=o,e[8]=l,e[9]=c,e[11]=s,e[12]=h,e[13]=d,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=a,t[4]=e[1],t[5]=e[5],t[6]=n,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],a=e[5],n=e[6],l=e[7],h=e[8],c=e[9],d=e[10],u=e[11],p=e[12],m=e[13],_=e[14],g=e[15];return p*c*n*r-h*m*n*r-p*a*d*r+o*m*d*r+h*a*_*r-o*c*_*r-p*c*s*l+h*m*s*l+p*i*d*l-t*m*d*l-h*i*_*l+t*c*_*l+p*a*s*u-o*m*s*u-p*i*n*u+t*m*n*u+o*i*_*u-t*a*_*u-h*a*s*g+o*c*s*g+h*i*n*g-t*c*n*g-o*i*d*g+t*a*d*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],n=e[5],l=e[6],h=e[7],c=e[8],d=e[9],u=e[10],p=e[11],m=e[12],_=e[13],g=e[14],f=e[15],v=i*n-s*a,b=i*l-r*a,y=i*h-o*a,M=s*l-r*n,w=s*h-o*n,x=r*h-o*l,P=c*_-d*m,E=c*g-u*m,A=c*f-p*m,C=d*g-u*_,S=d*f-p*_,R=u*f-p*g,L=1/(v*R-b*S+y*C+M*A-w*E+x*P);return t[0]=(n*R-l*S+h*C)*L,t[1]=(-s*R+r*S-o*C)*L,t[2]=(_*x-g*w+f*M)*L,t[3]=(-d*x+u*w-p*M)*L,t[4]=(-a*R+l*A-h*E)*L,t[5]=(i*R-r*A+o*E)*L,t[6]=(-m*x+g*y-f*b)*L,t[7]=(c*x-u*y+p*b)*L,t[8]=(a*S-n*A+h*P)*L,t[9]=(-i*S+s*A-o*P)*L,t[10]=(m*w-_*y+f*v)*L,t[11]=(-c*w+d*y-p*v)*L,t[12]=(-a*C+n*E-l*P)*L,t[13]=(i*C-s*E+r*P)*L,t[14]=(-m*M+_*b-g*v)*L,t[15]=(c*M-d*b+u*v)*L,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||math.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||math.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new Float32Array(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,math.translationMat4v(e,r))})(),translationMat4s:(e,t)=>math.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>math.translateMat4c(e[0],e[1],e[2],t),OLDtranslateMat4c(e,t,i,s){const r=s[12];s[0]+=r*e,s[4]+=r*t,s[8]+=r*i;const o=s[13];s[1]+=o*e,s[5]+=o*t,s[9]+=o*i;const a=s[14];s[2]+=a*e,s[6]+=a*t,s[10]+=a*i;const n=s[15];return s[3]+=n*e,s[7]+=n*t,s[11]+=n*i,s},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 a=s[11];s[8]+=a*e,s[9]+=a*t,s[10]+=a*i;const n=s[15];return s[12]+=n*e,s[13]+=n*t,s[14]+=n*i,s},rotationMat4v(e,t,i){const s=math.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),a=1-o,n=s[0],l=s[1],h=s[2];let c,d,u,p,m,_;return c=n*l,d=l*h,u=h*n,p=n*r,m=l*r,_=h*r,(i=i||math.mat4())[0]=a*n*n+o,i[1]=a*c+_,i[2]=a*u-m,i[3]=0,i[4]=a*c-_,i[5]=a*l*l+o,i[6]=a*d+p,i[7]=0,i[8]=a*u+m,i[9]=a*d-p,i[10]=a*h*h+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>math.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=math.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=math.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new Float32Array(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,math.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=>math.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=math.mat4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=s+s,l=r+r,h=o+o,c=s*n,d=s*l,u=s*h,p=r*l,m=r*h,_=o*h,g=a*n,f=a*l,v=a*h;return i[0]=1-(p+_),i[1]=d+v,i[2]=u-f,i[3]=0,i[4]=d-v,i[5]=1-(c+_),i[6]=m+g,i[7]=0,i[8]=u+f,i[9]=m-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=math.vec4()){const s=math.clamp,r=e[0],o=e[4],a=e[8],n=e[1],l=e[5],h=e[9],c=e[2],d=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-h,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(d,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(a,u),i[2]=Math.atan2(n,l)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(d,-1,1)),Math.abs(d)<.99999?(i[1]=Math.atan2(-c,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(n,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(d,u),i[2]=Math.atan2(n,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-h,l),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(a,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(d,l),i[1]=Math.atan2(a,r)):(i[0]=Math.atan2(-h,u),i[1]=0)),i},composeMat4:(e,t,i,s=math.mat4())=>(math.quaternionToRotationMat4(t,s),math.scaleMat4v(i,s),math.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new Float32Array(3),t=new Float32Array(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let a=math.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const n=math.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=math.lenVec3(e);math.determinantMat4(i)<0&&(a=-a),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const h=1/a,c=1/n,d=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=d,t[9]*=d,t[10]*=d,math.mat4ToQuaternion(t,r),o[0]=a,o[1]=n,o[2]=l,this}})(),lookAtMat4v(e,t,i,s){s||(s=math.mat4());const r=e[0],o=e[1],a=e[2],n=i[0],l=i[1],h=i[2],c=t[0],d=t[1],u=t[2];if(r===c&&o===d&&a===u)return math.identityMat4();let p,m,_,g,f,v,b,y,M,w;return p=r-c,m=o-d,_=a-u,g=l*(_*=w=1/Math.sqrt(p*p+m*m+_*_))-h*(m*=w),f=h*(p*=w)-n*_,v=n*m-l*p,(w=Math.sqrt(g*g+f*f+v*v))?(g*=w=1/w,f*=w,v*=w):(g=0,f=0,v=0),b=m*v-_*f,y=_*g-p*v,M=p*f-m*g,(w=Math.sqrt(b*b+y*y+M*M))?(b*=w=1/w,y*=w,M*=w):(b=0,y=0,M=0),s[0]=g,s[1]=b,s[2]=p,s[3]=0,s[4]=f,s[5]=y,s[6]=m,s[7]=0,s[8]=v,s[9]=M,s[10]=_,s[11]=0,s[12]=-(g*r+f*o+v*a),s[13]=-(b*r+y*o+M*a),s[14]=-(p*r+m*o+_*a),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,a,n,l)=>math.lookAtMat4v([e,t,i],[s,r,o],[a,n,l],[]),orthoMat4c(e,t,i,s,r,o,a){a||(a=math.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/l,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/h,a[11]=0,a[12]=-(e+t)/n,a[13]=-(s+i)/l,a[14]=-(o+r)/h,a[15]=1,a},frustumMat4v(e,t,i){i||(i=math.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];math.addVec4(r,s,tempMat1),math.subVec4(r,s,tempMat2);const o=2*s[2],a=tempMat2[0],n=tempMat2[1],l=tempMat2[2];return i[0]=o/a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/n,i[6]=0,i[7]=0,i[8]=tempMat1[0]/a,i[9]=tempMat1[1]/n,i[10]=-tempMat1[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,a){a||(a=math.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2*r/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2*r/l,a[6]=0,a[7]=0,a[8]=(t+e)/n,a[9]=(s+i)/l,a[10]=-(o+r)/h,a[11]=-1,a[12]=0,a[13]=0,a[14]=-o*r*2/h,a[15]=0,a},perspectiveMat4(e,t,i,s,r){const o=[],a=[];return o[2]=i,a[2]=s,a[1]=o[2]*Math.tan(e/2),o[1]=-a[1],a[0]=a[1]*t,o[0]=-a[0],math.frustumMat4v(o,a,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=math.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=math.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,a,n,l;const h=e[0],c=e[1],d=e[2],u=e[3],p=e[4],m=e[5],_=e[6],g=e[7],f=e[8],v=e[9],b=e[10],y=e[11],M=e[12],w=e[13],x=e[14],P=e[15];let E;for(let e=0;e<r;++e)o=(l=t[e])[0],a=l[1],n=l[2],(E=s[e]||(s[e]=[0,0,0]))[0]=h*o+p*a+f*n+M,E[1]=c*o+m*a+v*n+w,E[2]=d*o+_*a+b*n+x,E[3]=u*o+g*a+y*n+P;return s.length=r,s},transformPositions3(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],d=e[3],u=e[4],p=e[5],m=e[6],_=e[7],g=e[8],f=e[9],v=e[10],b=e[11],y=e[12],M=e[13],w=e[14],x=e[15];for(s=0;s<r;s+=3)o=t[s+0],a=t[s+1],n=t[s+2],i[s+0]=l*o+u*a+g*n+y,i[s+1]=h*o+p*a+f*n+M,i[s+2]=c*o+m*a+v*n+w,i[s+3]=d*o+_*a+b*n+x;return i},transformPositions4(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],d=e[3],u=e[4],p=e[5],m=e[6],_=e[7],g=e[8],f=e[9],v=e[10],b=e[11],y=e[12],M=e[13],w=e[14],x=e[15];for(s=0;s<r;s+=4)o=t[s+0],a=t[s+1],n=t[s+2],i[s+0]=l*o+u*a+g*n+y,i[s+1]=h*o+p*a+f*n+M,i[s+2]=c*o+m*a+v*n+w,i[s+3]=d*o+_*a+b*n+x;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],a=t[3];return(i=i||math.vec4())[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*a,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*a,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*a,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*a,i},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||math.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(()=>{const e=new Float32Array(16),t=new Float32Array(16),i=new Float32Array(16);return function(s,r,o,a){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,a)}})(),lerpVec3(e,t,i,s,r,o){const a=o||math.vec3(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a},lerpMat4(e,t,i,s,r,o){const a=o||math.mat4(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a[3]=s[3]+n*(r[3]-s[3]),a[4]=s[4]+n*(r[4]-s[4]),a[5]=s[5]+n*(r[5]-s[5]),a[6]=s[6]+n*(r[6]-s[6]),a[7]=s[7]+n*(r[7]-s[7]),a[8]=s[8]+n*(r[8]-s[8]),a[9]=s[9]+n*(r[9]-s[9]),a[10]=s[10]+n*(r[10]-s[10]),a[11]=s[11]+n*(r[11]-s[11]),a[12]=s[12]+n*(r[12]-s[12]),a[13]=s[13]+n*(r[13]-s[13]),a[14]=s[14]+n*(r[14]-s[14]),a[15]=s[15]+n*(r[15]-s[15]),a},flatten(e){const t=[];let i,s,r,o,a;for(i=0,s=e.length;i<s;i++)for(r=0,o=(a=e[i]).length;r<o;r++)t.push(a[r]);return t},identityQuaternion:(e=math.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=math.vec4()){const s=e[0]*math.DEGTORAD/2,r=e[1]*math.DEGTORAD/2,o=e[2]*math.DEGTORAD/2,a=Math.cos(s),n=Math.cos(r),l=Math.cos(o),h=Math.sin(s),c=Math.sin(r),d=Math.sin(o);return"XYZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"YXZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"ZXY"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"ZYX"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"YZX"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l-h*c*d):"XZY"===t&&(i[0]=h*n*l-a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l+h*c*d),i},mat4ToQuaternion(e,t=math.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],a=e[5],n=e[9],l=e[2],h=e[6],c=e[10];let d;const u=i+a+c;return u>0?(d=.5/Math.sqrt(u+1),t[3]=.25/d,t[0]=(h-n)*d,t[1]=(r-l)*d,t[2]=(o-s)*d):i>a&&i>c?(d=2*Math.sqrt(1+i-a-c),t[3]=(h-n)/d,t[0]=.25*d,t[1]=(s+o)/d,t[2]=(r+l)/d):a>c?(d=2*Math.sqrt(1+a-i-c),t[3]=(r-l)/d,t[0]=(s+o)/d,t[1]=.25*d,t[2]=(n+h)/d):(d=2*Math.sqrt(1+c-i-a),t[3]=(o-s)/d,t[0]=(r+l)/d,t[1]=(n+h)/d,t[2]=.25*d),t},vec3PairToQuaternion(e,t,i=math.vec4()){const s=Math.sqrt(math.dotVec3(e,e)*math.dotVec3(t,t));let r=s+math.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])):math.cross3Vec3(e,t,i),i[3]=r,math.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=math.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 Float32Array(16);return(t,i,s)=>(s=s||math.vec3(),math.quaternionToRotationMat4(t,e),math.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=math.vec4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=t[0],l=t[1],h=t[2],c=t[3];return i[0]=a*n+s*c+r*h-o*l,i[1]=a*l+r*c+o*n-s*h,i[2]=a*h+o*c+s*l-r*n,i[3]=a*c-s*n-r*l-o*h,i},vec3ApplyQuaternion(e,t,i=math.vec3()){const s=t[0],r=t[1],o=t[2],a=e[0],n=e[1],l=e[2],h=e[3],c=h*s+n*o-l*r,d=h*r+l*s-a*o,u=h*o+a*r-n*s,p=-a*s-n*r-l*o;return i[0]=c*h+p*-a+d*-l-u*-n,i[1]=d*h+p*-n+u*-a-c*-l,i[2]=u*h+p*-l+c*-n-d*-a,i},quaternionToMat4(e,t){t=math.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],a=2*i,n=2*s,l=2*r,h=a*o,c=n*o,d=l*o,u=a*i,p=n*i,m=l*i,_=n*s,g=l*s,f=l*r;return t[0]=1-(_+f),t[1]=p+d,t[2]=m-c,t[4]=p-d,t[5]=1-(u+f),t[6]=g+h,t[8]=m+c,t[9]=g-h,t[10]=1-(u+_),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],a=i+i,n=s+s,l=r+r,h=i*a,c=i*n,d=i*l,u=s*n,p=s*l,m=r*l,_=o*a,g=o*n,f=o*l;return t[0]=1-(u+m),t[4]=c-f,t[8]=d+g,t[1]=c+f,t[5]=1-(h+m),t[9]=p-_,t[2]=d-g,t[6]=p+_,t[10]=1-(h+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=math.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)=>math.normalizeQuaternion(math.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=math.vec4()){const i=(e=math.normalizeQuaternion(e,tempVec4))[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 Float32Array(e||6),AABB2:e=>new Float32Array(e||4),OBB3:e=>new Float32Array(e||32),OBB2:e=>new Float32Array(e||16),Sphere3:(e,t,i,s)=>new Float32Array([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],d=e[3],u=e[4],p=e[5],m=e[6],_=e[7],g=e[8],f=e[9],v=e[10],b=e[11],y=e[12],M=e[13],w=e[14],x=e[15];for(s=0;s<r;s+=4)o=t[s+0],a=t[s+1],n=t[s+2],i[s+0]=l*o+u*a+g*n+y,i[s+1]=h*o+p*a+f*n+M,i[s+2]=c*o+m*a+v*n+w,i[s+3]=d*o+_*a+b*n+x;return i},getAABB3Diag:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(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],math.subVec3(t,e,i),Math.abs(math.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(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=math.subVec3(t,e,i),a=r[0]-s[0],n=s[3]-r[0],l=r[1]-s[1],h=s[4]-r[1],c=r[2]-s[2],d=s[5]-r[2];return o[0]+=a>n?a:n,o[1]+=l>h?l:h,o[2]+=c>d?c:d,Math.abs(math.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||math.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||math.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=math.AABB3())=>(e[0]=math.MAX_DOUBLE,e[1]=math.MAX_DOUBLE,e[2]=math.MAX_DOUBLE,e[3]=-math.MAX_DOUBLE,e[4]=-math.MAX_DOUBLE,e[5]=-math.MAX_DOUBLE,e),AABB3ToOBB3:(e,t=math.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 Float32Array(3);return(t,i,s)=>{i=i||math.AABB3();let r,o,a,n=math.MAX_DOUBLE,l=math.MAX_DOUBLE,h=math.MAX_DOUBLE,c=-math.MAX_DOUBLE,d=-math.MAX_DOUBLE,u=-math.MAX_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],math.decompressPosition(e,s,e),r=e[0],o=e[1],a=e[2]):(r=t[i+0],o=t[i+1],a=t[i+2]),r<n&&(n=r),o<l&&(l=o),a<h&&(h=a),r>c&&(c=r),o>d&&(d=o),a>u&&(u=a);return i[0]=n,i[1]=l,i[2]=h,i[3]=c,i[4]=d,i[5]=u,i}})(),OBB3ToAABB3(e,t=math.AABB3()){let i,s,r,o=math.MAX_DOUBLE,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=-math.MAX_DOUBLE,h=-math.MAX_DOUBLE,c=-math.MAX_DOUBLE;for(let t=0,d=e.length;t<d;t+=4)i=e[t+0],s=e[t+1],r=e[t+2],i<o&&(o=i),s<a&&(a=s),r<n&&(n=r),i>l&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=math.AABB3()){let i,s,r,o=math.MAX_DOUBLE,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=-math.MAX_DOUBLE,h=-math.MAX_DOUBLE,c=-math.MAX_DOUBLE;for(let t=0,d=e.length;t<d;t++)i=e[t][0],s=e[t][1],r=e[t][2],i<o&&(o=i),s<a&&(a=s),r<n&&(n=r),i>l&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new Float32Array(3);return(t,i)=>{i=i||math.vec4();let s,r=0,o=0,a=0;const n=t.length;for(s=0;s<n;s++)r+=t[s][0],o+=t[s][1],a+=t[s][2];i[0]=r/n,i[1]=o/n,i[2]=a/n;let l,h=0;for(s=0;s<n;s++)(l=Math.abs(math.lenVec3(math.subVec3(t[s],i,e))))>h&&(h=l);return i[3]=h,i}})(),positions3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||math.vec4();let r,o=0,a=0,n=0;const l=i.length;let h=0;for(r=0;r<l;r+=3)o+=i[r],a+=i[r+1],n+=i[r+2];const c=l/3;let d;for(s[0]=o/c,s[1]=a/c,s[2]=n/c,r=0;r<l;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],(d=Math.abs(math.lenVec3(math.subVec3(e,s,t))))>h&&(h=d);return s[3]=h,s}})(),OBB3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||math.vec4();let r,o=0,a=0,n=0;const l=i.length,h=l/4;for(r=0;r<l;r+=4)o+=i[r+0],a+=i[r+1],n+=i[r+2];s[0]=o/h,s[1]=a/h,s[2]=n/h;let c,d=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(math.lenVec3(math.subVec3(e,s,t))))>d&&(d=c);return s[3]=d,s}})(),getSphere3Center:(e,t=math.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],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,a=t.length;o<a;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=math.AABB2())=>(e[0]=math.MAX_DOUBLE,e[1]=math.MAX_DOUBLE,e[2]=-math.MAX_DOUBLE,e[3]=-math.MAX_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],OBB3ToAABB2(e,t=math.AABB2()){let i,s,r,o,a=math.MAX_DOUBLE,n=math.MAX_DOUBLE,l=-math.MAX_DOUBLE,h=-math.MAX_DOUBLE;for(let t=0,c=e.length;t<c;t+=4)i=e[t+0],s=e[t+1],s*=o=1/(r=e[t+3]||1),(i*=o)<a&&(a=i),s<n&&(n=s),i>l&&(l=i),s>h&&(h=s);return t[0]=a,t[1]=n,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<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),a=.5*(e[2]+1),n=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(n*i),s[2]=Math.floor(a*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),a=.5*(s-t),n=r*r;return(2*t-2*i+o+a)*(r*n)+(-3*t+3*i-2*o-a)*n+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=math.vec3()){const r=t[0]-e[0],o=t[1]-e[1],a=t[2]-e[2],n=i[0]-e[0],l=i[1]-e[1],h=i[2]-e[2],c=o*h-a*l,d=a*n-r*h,u=r*l-o*n,p=Math.sqrt(c*c+d*d+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/p,s[1]=d/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3);return(o,a,n,l,h,c)=>{c=c||math.vec3();const d=math.subVec3(l,n,e),u=math.subVec3(h,n,t),p=math.cross3Vec3(a,u,i),m=math.dotVec3(d,p);if(m<1e-6)return null;const _=math.subVec3(o,n,s),g=math.dotVec3(_,p);if(g<0||g>m)return null;const f=math.cross3Vec3(_,d,r),v=math.dotVec3(a,f);if(v<0||g+v>m)return null;const b=math.dotVec3(u,f)/m;return c[0]=o[0]+b*a[0],c[1]=o[1]+b*a[1],c[2]=o[2]+b*a[2],c}})(),rayPlaneIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3);return(r,o,a,n,l,h)=>{h=h||math.vec3(),o=math.normalizeVec3(o,e);const c=math.subVec3(n,a,t),d=math.subVec3(l,a,i),u=math.cross3Vec3(c,d,s);math.normalizeVec3(u,u);const p=-math.dotVec3(a,u),m=-(math.dotVec3(r,u)+p)/math.dotVec3(o,u);return h[0]=r[0]+m*o[0],h[1]=r[1]+m*o[1],h[2]=r[2]+m*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3);return(s,r,o,a,n)=>{const l=math.subVec3(a,r,e),h=math.subVec3(o,r,t),c=math.subVec3(s,r,i),d=math.dotVec3(l,l),u=math.dotVec3(l,h),p=math.dotVec3(l,c),m=math.dotVec3(h,h),_=math.dotVec3(h,c),g=d*m-u*u;if(0===g)return null;const f=1/g,v=(m*p-u*_)*f,b=(d*_-u*p)*f;return n[0]=1-v-b,n[1]=b,n[2]=v,n}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=math.vec3()){const o=e[0],a=e[1],n=e[2];return r[0]=t[0]*o+i[0]*a+s[0]*n,r[1]=t[1]*o+i[1]*a+s[1]*n,r[2]=t[2]*o+i[2]*a+s[2]*n,r},mergeVertices(e,t,i,s){const r={},o=[],a=[],n=t?[]:null,l=i?[]:null,h=[];let c,d,u,p;let m,_,g=0;for(m=0,_=e.length;m<_;m+=3)c=e[m],d=e[m+1],u=e[m+2],void 0===r[p=`${Math.round(1e4*c)}_${Math.round(1e4*d)}_${Math.round(1e4*u)}`]&&(r[p]=a.length/3,a.push(c),a.push(d),a.push(u),t&&(n.push(t[m]),n.push(t[m+1]),n.push(t[m+2])),i&&(l.push(i[g]),l.push(i[g+1]))),o[m/3]=r[p],g+=2;for(m=0,_=s.length;m<_;m++)h[m]=o[s[m]];const f={positions:a,indices:h};return n&&(f.normals=n),l&&(f.uv=l),f},buildNormals:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3);return(a,n,l)=>{let h,c;const d=new Array(a.length/3);let u,p,m,_,g,f,v;for(h=0,c=n.length;h<c;h+=3){u=n[h],p=n[h+1],m=n[h+2],e[0]=a[3*u],e[1]=a[3*u+1],e[2]=a[3*u+2],t[0]=a[3*p],t[1]=a[3*p+1],t[2]=a[3*p+2],i[0]=a[3*m],i[1]=a[3*m+1],i[2]=a[3*m+2],math.subVec3(t,e,s),math.subVec3(i,e,r);const l=new Float32Array(3);math.normalizeVec3(math.cross3Vec3(s,r,o),l),d[u]||(d[u]=[]),d[p]||(d[p]=[]),d[m]||(d[m]=[]),d[u].push(l),d[p].push(l),d[m].push(l)}for(l=l&&l.length===a.length?l:new Float32Array(a.length),h=0,c=d.length;h<c;h++){_=d[h].length,g=0,f=0,v=0;for(let e=0;e<_;e++)g+=d[h][e][0],f+=d[h][e][1],v+=d[h][e][2];l[3*h]=g/_,l[3*h+1]=f/_,l[3*h+2]=v/_}return l}})(),buildTangents:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3),a=new Float32Array(3);return(n,l,h)=>{const c=new Float32Array(n.length);for(let d=0;d<l.length;d+=3){let u=l[d];const p=n.subarray(3*u,3*u+3),m=h.subarray(2*u,2*u+2);u=l[d+1];const _=n.subarray(3*u,3*u+3),g=h.subarray(2*u,2*u+2);u=l[d+2];const f=n.subarray(3*u,3*u+3),v=h.subarray(2*u,2*u+2),b=math.subVec3(_,p,e),y=math.subVec3(f,p,t),M=math.subVec2(g,m,i),w=math.subVec2(v,m,s),x=1/(M[0]*w[1]-M[1]*w[0]),P=math.mulVec3Scalar(math.subVec3(math.mulVec3Scalar(b,w[1],r),math.mulVec3Scalar(y,M[1],o),a),x,o);let E;for(let e=0;e<3;e++)c[E=3*l[d+e]]+=P[0],c[E+1]+=P[1],c[E+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 a,n,l,h,c,d,u=0,p=0,m=0;for(let i=0;i<s;i+=3)d=u>>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=3*(n=t[i]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,a=3*(n=t[i+1]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,a=3*(n=t[i+2]),r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[m++]=l,o[m++]=h,o[m++]=c,o[m++]=d,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],a={};let n,l,h,c,d;let u,p,m,_,g,f;for(p=0,_=e.length;p<_;p+=3){u=p/3,l=e[p],h=e[p+1],c=e[p+2],void 0===r[d=`${Math.round(1e4*l)}_${Math.round(1e4*h)}_${Math.round(1e4*c)}`]?r[d]=[u]:r[d].push(u);const i=math.normalizeVec3([t[p],t[p+1],t[p+2]]);o[u]=i,n=math.vec4([i[0],i[1],i[2],1]),a[u]=n}for(d in r)if(r.hasOwnProperty(d)){const e=r[d],t=e.length;for(p=0;p<t;p++){const i=e[p];for(n=a[i],m=0;m<t;m++){if(p===m)continue;const t=e[m];g=o[i],f=o[t],Math.abs(math.angleVec3(g,f)/math.DEGTORAD)<s&&(n[0]+=f[0],n[1]+=f[1],n[2]+=f[2],n[3]+=1)}}}for(p=0,_=t.length;p<_;p+=3)n=a[p/3],t[p+0]=n[0]/n[3],t[p+1]=n[1]/n[3],t[p+2]=n[2]/n[3]},canvasPosToWorldRay:(()=>{const e=new Float32Array(16),t=new Float32Array(16),i=new Float32Array(4),s=new Float32Array(4),r=new Float32Array(4),o=new Float32Array(4);return(a,n,l,h,c,d)=>{const u=math.mulMat4(l,n,e),p=math.inverseMat4(u,t),m=a.width,_=a.height,g=(h[0]-m/2)/(m/2),f=-(h[1]-_/2)/(_/2);i[0]=g,i[1]=f,i[2]=-1,i[3]=1,math.transformVec4(p,i,s),math.mulVec4Scalar(s,1/s[3]),r[0]=g,r[1]=f,r[2]=1,r[3]=1,math.transformVec4(p,r,o),math.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],math.subVec3(o,s,d),math.normalizeVec3(d)}})(),canvasPosToLocalRay:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s,r,o,a,n,l)=>{math.canvasPosToWorldRay(i,s,r,a,e,t),math.worldRayToLocalRay(o,e,t,n,l)}})(),worldRayToLocalRay:(()=>{const e=new Float32Array(16),t=new Float32Array(4),i=new Float32Array(4);return(s,r,o,a,n)=>{const l=math.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,math.transformVec4(l,t,i),a[0]=i[0],a[1]=i[1],a[2]=i[2],math.transformVec3(l,o,n)}})(),buildKDTree:(()=>{const e=10,t=20,i=new Float32Array;return(s,r)=>{const o=s.length/3,a=new Array(o);for(let e=0;e<o;++e)a[e]=e;return function s(r,o,a,n){const l=new Float32Array(6),h={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:l};let c,d;for(l[0]=l[1]=l[2]=Number.POSITIVE_INFINITY,l[3]=l[4]=l[5]=Number.NEGATIVE_INFINITY,c=0,d=r.length;c<d;++c){var u=3*r[c];for(let e=0;e<3;++e){const t=3*o[u+e];a[t]<l[0]&&(l[0]=a[t]),a[t]>l[3]&&(l[3]=a[t]),a[t+1]<l[1]&&(l[1]=a[t+1]),a[t+1]>l[4]&&(l[4]=a[t+1]),a[t+2]<l[2]&&(l[2]=a[t+2]),a[t+2]>l[5]&&(l[5]=a[t+2])}}if(r.length<t||n>e)return h.triangles=r,h.leaf=!0,h;i[0]=l[3]-l[0],i[1]=l[4]-l[1],i[2]=l[5]-l[2];let p=0;i[1]>i[p]&&(p=1),i[2]>i[p]&&(p=2),h.splitDim=p;const m=(l[p]+l[p+3])/2,_=new Array(r.length);let g=0;const f=new Array(r.length);let v=0;for(c=0,d=r.length;c<d;++c){const e=o[u=3*r[c]],t=3*o[u+1],i=3*o[u+2];a[3*e+p]<=m||a[t+p]<=m||a[i+p]<=m?_[g++]=r[c]:f[v++]=r[c]}return _.length=g,f.length=v,h.left=s(_,o,a,n+1),h.right=s(f,o,a,n+1),h}(a,s,r,0)}})(),decompressPosition(e,t,i){i[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 a=1-Math.abs(r)-Math.abs(o);a<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t}};math.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=math.vec3(),c=math.vec3(),d=math.vec3(),u=math.vec3(),p=math.vec3(),m=math.vec3(),_=math.vec3();return function(g,f,v,b){!function(r,o){const a={};let n,l,h,c;const d=Math.pow(10,4);let u,p,m=0;for(u=0,p=r.length;u<p;u+=3)n=r[u],l=r[u+1],h=r[u+2],void 0===a[c=Math.round(n*d)+"_"+Math.round(l*d)+"_"+Math.round(h*d)]&&(a[c]=m/3,e[m++]=n,e[m++]=l,e[m++]=h),t[u/3]=a[c];for(u=0,p=o.length;u<p;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,f),function(t,i){o=0;for(let g=0,f=t;g<f;g+=3){const t=3*s[g],f=3*s[g+1],v=3*s[g+2];i?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],n[0]=e[f],n[1]=e[f+1],n[2]=e[f+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],math.decompressPosition(a,i,h),math.decompressPosition(n,i,c),math.decompressPosition(l,i,d)):(h[0]=e[t],h[1]=e[t+1],h[2]=e[t+2],c[0]=e[f],c[1]=e[f+1],c[2]=e[f+2],d[0]=e[v],d[1]=e[v+1],d[2]=e[v+2]),math.subVec3(d,c,u),math.subVec3(h,c,p),math.cross3Vec3(u,p,m),math.normalizeVec3(m,_);const b=r[o]||(r[o]={normal:math.vec3()});b.normal[0]=_[0],b.normal[1]=_[1],b.normal[2]=_[2],o++}}(f.length,v);const y=[],M=Math.cos(math.DEGTORAD*b),w={};let x,P,E,A,C,S,R,L,D,k,T,I=!1;for(let e=0,t=f.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],void 0===w[C=(E=Math.min(x,P))+","+(A=Math.max(x,P))]?w[C]={index1:E,index2:A,face1:t,face2:void 0}:w[C].face2=t}for(C in w)void 0!==(S=w[C]).face2&&(R=r[S.face1].normal,L=r[S.face2].normal,(D=math.dotVec3(R,L))>M)||(k=i[S.index1],T=i[S.index2],(!I&&k>65535||T>65535)&&(I=!0),y.push(k),y.push(T));return I?new Uint32Array(y):new Uint16Array(y)}}();const color=math.vec3();class ModelMemento{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){const s=t.rootMetaObject;if(!s)return;const r=s.getObjectIDsInSubtree();this.numObjects=0,this._mask=i?utils.apply(i,{}):null;const o=e.objects,a=!i||i.visible,n=!i||i.edges,l=!i||i.xrayed,h=!i||i.highlighted,c=!i||i.selected,d=!i||i.clippable,u=!i||i.pickable,p=!i||i.colorize,m=!i||i.opacity;for(var _=0,g=r.length;_<g;_++){const e=o[r[_]];if(e){if(a&&(this.objectsVisible[_]=e.visible),n&&(this.objectsEdges[_]=e.edges),l&&(this.objectsXrayed[_]=e.xrayed),h&&(this.objectsHighlighted[_]=e.highlighted),c&&(this.objectsSelected[_]=e.selected),d&&(this.objectsClippable[_]=e.clippable),u&&(this.objectsPickable[_]=e.pickable),p){const t=e.colorize;this.objectsColorize[3*_+0]=t[0],this.objectsColorize[3*_+1]=t[1],this.objectsColorize[3*_+2]=t[2]}m&&(this.objectsOpacity[_]=e.opacity),this.numObjects++}}}restoreObjects(e,t){const i=t.rootMetaObject;if(!i)return;const s=i.getObjectIDsInSubtree(),r=this._mask,o=!r||r.visible,a=!r||r.edges,n=!r||r.xrayed,l=!r||r.highlighted,h=!r||r.selected,c=!r||r.clippable,d=!r||r.pickable,u=!r||r.colorize,p=!r||r.opacity,m=e.objects;for(var _=0,g=s.length;_<g;_++){const e=m[s[_]];e&&(o&&(e.visible=this.objectsVisible[_]),a&&(e.edges=this.objectsEdges[_]),n&&(e.xrayed=this.objectsXrayed[_]),l&&(e.highlighted=this.objectsHighlighted[_]),h&&(e.selected=this.objectsSelected[_]),c&&(e.clippable=this.objectsClippable[_]),d&&(e.pickable=this.objectsPickable[_]),u&&(color[0]=this.objectsColorize[3*_+0],color[1]=this.objectsColorize[3*_+1],color[2]=this.objectsColorize[3*_+2],e.colorize=color),p&&(e.opacity=this.objectsOpacity[_]))}}}const tempVec3a=math.vec3();class ResetAction extends Controller{constructor(e,t={}){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement,s=this.viewer.camera;this._modelMementos={},s.eye=[.577,.577,.577],s.look=[0,0,0],s.up=[-1,1,-1],this.bimViewer._modelsExplorer.on("modelLoaded",e=>{this._saveModelMemento(e)}),this.bimViewer._modelsExplorer.on("modelUnloaded",e=>{this._destroyModelMemento(e)}),this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{this.getEnabled()&&this.reset(),e.preventDefault()})}_saveModelMemento(e){const t=this.viewer.metaScene.metaModels[e];if(!t)return;const i=new ModelMemento;i.saveObjects(this.viewer.scene,t,{visible:!0,edges:!0,xrayed:!0,highlighted:!0,selected:!0,clippable:!0,pickable:!0,colorize:!0,opacity:!1}),this._modelMementos[e]=i}_restoreModelMemento(e){const t=this.viewer.metaScene.metaModels[e];t&&this._modelMementos[e].restoreObjects(this.viewer.scene,t)}_destroyModelMemento(e){delete this._modelMementos[e]}reset(){const e=this.viewer.scene.modelIds;for(var t=0,i=e.length;t<i;t++){const i=e[t];this._restoreModelMemento(i)}this.bimViewer.unShowObjectInExplorers(),this.fire("reset",!0),this._resetCamera()}_resetCamera(){const e=this.viewer,t=e.scene,i=t.getAABB(t.visibleObjectIds),s=math.getAABB3Diag(i),r=math.getAABB3Center(i,tempVec3a),o=Math.abs(s/Math.tan(32.5)),a=t.camera,n=a.yUp?[-1,-1,-1]:[1,1,1],l=a.yUp?[-1,1,-1]:[-1,1,1];e.cameraControl.pivotPos=r,e.cameraControl.planView=!1,e.cameraFlight.flyTo({look:r,eye:[r[0]-o*n[0],r[1]-o*n[1],r[2]-o*n[2]],up:l,orthoScale:1.3*s,projection:"perspective",duration:1})}}const tempVec3=math.vec3();class FitAction extends Controller{constructor(e,t={}){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{this.getEnabled()&&this.fit(),e.preventDefault()})}fit(){const e=this.viewer.scene,t=e.getAABB(e.visibleObjectIds);this.viewer.cameraFlight.flyTo({aabb:t}),this.viewer.cameraControl.pivotPos=math.getAABB3Center(t,tempVec3)}set fov(e){this.viewer.scene.cameraFlight.fitFOV=e}get fov(){return this.viewer.scene.cameraFlight.fitFOV}set duration(e){this.viewer.scene.cameraFlight.duration=e}get duration(){return this.viewer.scene.cameraFlight.duration}}class FirstPersonMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement,s=this.viewer.cameraControl,r=t.cameraControlNavModeMediator;s.navMode="orbit",s.followPointer=!0,this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),this.on("active",e=>{r.setFirstPersonModeActive(e),e?(s.followPointer=!0,s.pivoting=!1):s.pivoting=!0}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)})}}function closeEnough(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class HideTool extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?(i.classList.add("active"),this.viewer.cameraControl.doublePickFlyTo=!1):(i.classList.remove("active"),this.viewer.cameraControl.doublePickFlyTo=!0)}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._init()}_init(){var e=null;this._onHover=this.viewer.cameraControl.on("hover",t=>{this.getActive()&&this.getEnabled()&&(e&&(e.highlighted=!1,e=null),(e=t.entity).highlighted=!0)}),this._onHoverOff=this.viewer.cameraControl.on("hoverOff",t=>{this.getActive()&&this.getEnabled()&&e&&(e.highlighted=!1,e=null)});const t=math.vec2(),i=this.viewer.scene.input;this._onMousedown=i.on("mousedown",e=>{!i.mouseDownLeft||i.mouseDownRight||i.mouseDownMiddle||(t[0]=e[0],t[1]=e[1])}),this._onMouseup=i.on("mouseup",i=>{if(this.getActive()&&this.getEnabled()&&e){if(!closeEnough(t,i))return void(e=null);e.visible=!1,e.highlighted=!1,e=null}})}}function closeEnough$1(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class SelectionTool extends Controller{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._initSectionMode()}_initSectionMode(){const e=this.viewer,t=e.cameraControl;var i=null;this._onHover=t.on("hover",e=>{this.getActive()&&this.getEnabled()&&(i&&(i.highlighted=!1,i=null),(i=e.entity).highlighted=!0)}),this._onHoverOff=t.on("hoverOff",e=>{this.getActive()&&this.getEnabled()&&i&&(i.highlighted=!1,i=null)});const s=math.vec2(),r=e.scene.input;this._onMousedown=r.on("mousedown",e=>{this.getActive()&&this.getEnabled()&&(!r.mouseDownLeft||r.mouseDownRight||r.mouseDownMiddle||(s[0]=e[0],s[1]=e[1]))}),this._onMouseup=r.on("mouseup",e=>{if(this.getActive()&&this.getEnabled()&&i){if(!closeEnough$1(s,e))return void(i=null);i.selected=!i.selected,i=null}})}}function closeEnough$2(e,t){return Math.abs(e[0]-t[0])<4&&Math.abs(e[1]-t[1])<4}class QueryTool extends Controller{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")}),this.on("active",e=>{e?i.classList.add("active"):i.classList.remove("active")}),i.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!1)}),this._init()}_init(){const e=this.viewer,t=e.cameraControl;var i=null;this._onHover=t.on("hover",e=>{this.getActive()&&this.getEnabled()&&(i&&(i.highlighted=!1,i=null),(i=e.entity).highlighted=!0)}),this._onHoverOff=t.on("hoverOff",e=>{this.getActive()&&this.getEnabled()&&i&&(i.highlighted=!1,i=null)});const s=math.vec2(),r=e.scene.input;this._onMousedown=r.on("mousedown",e=>{this.getActive()&&this.getEnabled()&&(!r.mouseDownLeft||r.mouseDownRight||r.mouseDownMiddle||(s[0]=e[0],s[1]=e[1]))}),this._onMouseup=r.on("mouseup",t=>{if(this.getActive()&&this.getEnabled())if(i){if(!closeEnough$2(s,t))return void(i=null);const r=i.model;if(!r)return;const o=this.bimViewer.getLoadedProjectId();if(!o)return void this.error("Query tool: should be a project loaded - ignoring query-pick");const a=r.id,n=i.id,l=e.metaScene.metaObjects[n];if(!l)return;const h={projectId:o,modelId:a,objectId:n,objectName:l.name,objectType:l.type};this.fire("queryPicked",h),i=null}else this.fire("queryNotPicked",!1)})}}class Plugin{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._eventSubs={},t.addPlugin(this)}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}class Queue{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 stats={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}},scenesRenderInfo={},sceneIDMap=new Map,taskQueue=new Queue,tickEvent={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},taskBudget=10,fpsSamples=[],numFPSSamples=30;let elapsedTime,lastTime=0,totalFPS=0;function Core(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(core.scenes[e.id])return void console.error(`[ERROR] Scene ${utils.inQuotes(e.id)} already exists`)}else e.id=sceneIDMap.addItem({});core.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;scenesRenderInfo[e.id]={ticksPerOcclusionTest:t,occlusionTestCountdown:t,ticksPerRender:i,renderCountdown:i},stats.components.scenes++,e.once("destroyed",()=>{sceneIDMap.removeItem(e.id),delete core.scenes[e.id],delete scenesRenderInfo[e.id],stats.components.scenes--})},this.clear=function(){let e;for(const t in core.scenes)core.scenes.hasOwnProperty(t)&&(e=core.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete core.scenes[e.id]))},this.scheduleTask=function(e,t){taskQueue.push(e),taskQueue.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;taskQueue.length>0&&(e<0||s<e);)t=taskQueue.shift(),(i=taskQueue.shift())?t.call(i):t(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return taskQueue.length}}const core=new Core,frame=function(){let e=Date.now();if(lastTime>0){var t=1e3/(elapsedTime=e-lastTime);totalFPS+=t,fpsSamples.push(t),fpsSamples.length>=30&&(totalFPS-=fpsSamples.shift()),stats.frame.fps=Math.round(totalFPS/fpsSamples.length)}runTasks(e),fireTickEvents(e),renderScenes(),lastTime=e,window.requestAnimationFrame(frame)};function runTasks(e){const t=core.runTasks(e+taskBudget),i=core.getNumTasks();stats.frame.tasksRun=t,stats.frame.tasksScheduled=i,stats.frame.tasksBudget=taskBudget}function fireTickEvents(e){for(var t in tickEvent.time=e,core.scenes)if(core.scenes.hasOwnProperty(t)){var i=core.scenes[t];tickEvent.sceneId=t,tickEvent.startTime=i.startTime,tickEvent.deltaTime=null!=tickEvent.prevTime?tickEvent.time-tickEvent.prevTime:0,i.fire("tick",tickEvent,!0)}tickEvent.prevTime=e}function renderScenes(){const e=core.scenes;let t,i,s,r,o;for(o in e)e.hasOwnProperty(o)&&(t=e[o],(i=scenesRenderInfo[o])||(i=scenesRenderInfo[o]={}),s=t.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==s&&(i.ticksPerOcclusionTest=s,i.renderCountdown=s),0==--i.occlusionTestCountdown&&(t.doOcclusionTest(),i.occlusionTestCountdown=s),r=t.ticksPerRender,i.ticksPerRender!==r&&(i.ticksPerRender=r,i.renderCountdown=r),0==--i.renderCountdown&&(t.render(!1),i.renderCountdown=r))}window.requestAnimationFrame(frame);class Component{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 Component))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e,this._renderer=this.scene._renderer}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.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty()}glResort(){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(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Map),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);const r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;const o=this._events[e];return void 0!==o&&t.call(i||this,o),r}off(e){if(void 0===e||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+" "+utils.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,a=e.on,n=!1!==e.recompiles;if(i&&(utils.isNumeric(i)||utils.isString(i))){const e=i;if(!(i=this.scene.components[e]))return void this.error("Component not found: "+utils.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]))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+" "+utils.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+utils.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,d;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(c=0,d=(h=e.subs).length;c<d;c++)l.off(h[c]);delete this._attached[t],delete this._attachments[l.id];const s=e.params.onDetached;s&&(utils.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:!1};s.subs.push(i.once("destroyed",function(){s.params.component=null,this._attach(s.params)},this)),n&&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&&(utils.isFunction(r)?r(i):r.scope?r.callback.call(r.scope,i):r.callback(i)),a){let e,t,r,o;for(e in a)if(a.hasOwnProperty(e)){if(t=a[e],utils.isFunction(t)?(r=t,o=null):(r=t.callback,o=t.scope),!r)continue;s.subs.push(i.on(e,r,o))}}}return n&&this.fire("dirty",this),this.fire(t,i),i}_checkComponent(e,t){if(!t.isComponent){if(!utils.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(!utils.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():core.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(i=(t=this._attachments[e]).component,r=0,o=(s=t.subs).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]).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 ids=new Map({});class RenderState{constructor(e){this.id=ids.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ids.removeItem(this.id)}}class SectionPlane extends Component{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new RenderState({active:!0,pos:new Float32Array(3),dir:new Float32Array(3)}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this.glRedraw(),this.fire("pos",this._state.pos)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this.glRedraw(),this.fire("dir",this._state.dir)}get dir(){return this._state.dir}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}function buildCylinderGeometry(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 a=!!e.openEnded;let n=e.center;const l=n?n[0]:0,h=n?n[1]:0,c=n?n[2]:0,d=s/2,u=s/o,p=2*Math.PI/r,m=1/r,_=(t-i)/o,g=[],f=[],v=[],b=[];let y,M,w,x,P,E,A,C,S,R,L;const D=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*_,E=d-y*u,M=0;M<=r;M++)w=Math.sin(M*p),x=Math.cos(M*p),f.push(P*w),f.push(D),f.push(P*x),v.push(M*m),v.push(1*y/o),g.push(P*w+l),g.push(E+h),g.push(P*x+c);for(y=0;y<o;y++)for(M=0;M<=r;M++)C=(A=y*(r+1)+M)+r,b.push(A),b.push(C),b.push(C+1),b.push(A),b.push(C+1),b.push(A+1);if(!a&&t>0){for(S=g.length/3,f.push(0),f.push(1),f.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(d+h),g.push(0+c),M=0;M<=r;M++)w=Math.sin(M*p),x=Math.cos(M*p),R=.5*Math.sin(M*p)+.5,L=.5*Math.cos(M*p)+.5,f.push(t*w),f.push(1),f.push(t*x),v.push(R),v.push(L),g.push(t*w+l),g.push(d+h),g.push(t*x+c);for(M=0;M<r;M++)n=S,A=S+1+M,b.push(A),b.push(A+1),b.push(n)}if(!a&&i>0){for(S=g.length/3,f.push(0),f.push(-1),f.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(0-d+h),g.push(0+c),M=0;M<=r;M++)w=Math.sin(M*p),x=Math.cos(M*p),R=.5*Math.sin(M*p)+.5,L=.5*Math.cos(M*p)+.5,f.push(i*w),f.push(-1),f.push(i*x),v.push(R),v.push(L),g.push(i*w+l),g.push(0-d+h),g.push(i*x+c);for(M=0;M<r;M++)n=S,A=S+1+M,b.push(n),b.push(A+1),b.push(A)}return utils.apply(e,{positions:g,normals:f,uv:v,indices:b})}function buildTorusGeometry(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 a=e.center;let n=a?a[0]:0,l=a?a[1]:0;const h=a?a[2]:0,c=[],d=[],u=[],p=[];let m,_,g,f,v,b,y,M,w,x,P,E;for(M=0;M<=r;M++)for(y=0;y<=s;y++)m=y/s*o,_=.785398+M/r*Math.PI*2,n=t*Math.cos(m),l=t*Math.sin(m),g=(t+i*Math.cos(_))*Math.cos(m),f=(t+i*Math.cos(_))*Math.sin(m),v=i*Math.sin(_),c.push(g+n),c.push(f+l),c.push(v+h),u.push(1-y/s),u.push(M/r),b=math.normalizeVec3(math.subVec3([g,f,v],[n,l,h],[]),[]),d.push(b[0]),d.push(b[1]),d.push(b[2]);for(M=1;M<=r;M++)for(y=1;y<=s;y++)w=(s+1)*M+y-1,x=(s+1)*(M-1)+y-1,P=(s+1)*(M-1)+y,E=(s+1)*M+y,p.push(w),p.push(x),p.push(P),p.push(P),p.push(E),p.push(w);return utils.apply(e,{positions:c,normals:d,uv:u,indices:p})}function buildBoxGeometry(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,a=r?r[1]:0,n=r?r[2]:0,l=-t+o,h=-i+a,c=-s+n,d=t+o,u=i+a,p=s+n;return utils.apply(e,{positions:[d,u,p,l,u,p,l,h,p,d,h,p,d,u,p,d,h,p,d,h,c,d,u,c,d,u,p,d,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,d,h,c,d,h,p,l,h,p,d,h,c,l,h,c,l,u,c,d,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Geometry extends Component{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),stats.memory.meshes++}destroy(){super.destroy(),stats.memory.meshes--}}class ArrayBuf{constructor(e,t,i,s,r,o,a,n,l){switch(this._gl=e,this.type=t,this.allocated=!1,i.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=o,this.length=0,this.dataLength=s,this.numItems=0,this.itemSize=r,this.normalized=!!a,this.stride=n||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)))}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)}}const WEBGL_INFO={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},canvas=document.createElement("canvas");if(canvas){const e=canvas.getContext("webgl",{antialias:!0})||canvas.getContext("experimental-webgl",{antialias:!0});WEBGL_INFO.WEBGL=!!e,WEBGL_INFO.WEBGL&&(WEBGL_INFO.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?WEBGL_INFO.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?WEBGL_INFO.FS_MAX_FLOAT_PRECISION="mediump":WEBGL_INFO.FS_MAX_FLOAT_PRECISION="lowp":WEBGL_INFO.FS_MAX_FLOAT_PRECISION="mediump",WEBGL_INFO.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),WEBGL_INFO.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),WEBGL_INFO.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),WEBGL_INFO.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),WEBGL_INFO.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),WEBGL_INFO.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),WEBGL_INFO.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),WEBGL_INFO.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),WEBGL_INFO.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),WEBGL_INFO.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach(function(e){WEBGL_INFO.SUPPORTED_EXTENSIONS[e]=!0}),WEBGL_INFO.depthTexturesSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.WEBGL_depth_texture)}var buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=math.vec3(),c=math.vec3(),d=math.vec3(),u=math.vec3(),p=math.vec3(),m=math.vec3(),_=math.vec3();return function(g,f,v,b){!function(r,o){const a={};let n,l,h,c;const d=Math.pow(10,4);let u,p,m=0;for(u=0,p=r.length;u<p;u+=3)n=r[u],l=r[u+1],h=r[u+2],void 0===a[c=Math.round(n*d)+"_"+Math.round(l*d)+"_"+Math.round(h*d)]&&(a[c]=m/3,e[m++]=n,e[m++]=l,e[m++]=h),t[u/3]=a[c];for(u=0,p=o.length;u<p;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,f),function(t,i){o=0;for(let g=0,f=t;g<f;g+=3){const t=3*s[g],f=3*s[g+1],v=3*s[g+2];i?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],n[0]=e[f],n[1]=e[f+1],n[2]=e[f+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],math.decompressPosition(a,i,h),math.decompressPosition(n,i,c),math.decompressPosition(l,i,d)):(h[0]=e[t],h[1]=e[t+1],h[2]=e[t+2],c[0]=e[f],c[1]=e[f+1],c[2]=e[f+2],d[0]=e[v],d[1]=e[v+1],d[2]=e[v+2]),math.subVec3(d,c,u),math.subVec3(h,c,p),math.cross3Vec3(u,p,m),math.normalizeVec3(m,_);const b=r[o]||(r[o]={normal:math.vec3()});b.normal[0]=_[0],b.normal[1]=_[1],b.normal[2]=_[2],o++}}(f.length,v);const y=[],M=Math.cos(math.DEGTORAD*b),w={};let x,P,E,A,C,S,R,L,D,k,T,I=!1;for(let e=0,t=f.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],void 0===w[C=(E=Math.min(x,P))+","+(A=Math.max(x,P))]?w[C]={index1:E,index2:A,face1:t,face2:void 0}:w[C].face2=t}for(C in w)void 0!==(S=w[C]).face2&&(R=r[S.face1].normal,L=r[S.face2].normal,(D=math.dotVec3(R,L))>M)||(k=i[S.index1],T=i[S.index2],(!I&&k>65535||T>65535)&&(I=!0),y.push(k),y.push(T));return I?new Uint32Array(y):new Uint16Array(y)}}();function getPositionsBounds(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}}var compressPositions=function(){const e=math.mat4(),t=math.mat4();return function(i,s,r){const o=new Uint16Array(i.length);var a=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let n;for(n=0;n<i.length;n+=3)o[n+0]=Math.floor((i[n+0]-s[0])*a[0]),o[n+1]=Math.floor((i[n+1]-s[1])*a[1]),o[n+2]=Math.floor((i[n+2]-s[2])*a[2]);return math.identityMat4(e),math.translationMat4v(s,e),math.identityMat4(t),math.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t),{quantized:o,decodeMatrix:math.mulMat4(e,t,math.identityMat4())}}}();function decompressPosition(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}function decompressAABB(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}function 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}function getUVBounds(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}}var compressUVs=function(){const e=math.mat3(),t=math.mat3();return function(i,s,r){const o=new Uint16Array(i.length),a=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);let n;for(n=0;n<i.length;n+=2)o[n+0]=Math.floor((i[n+0]-s[0])*a[0]),o[n+1]=Math.floor((i[n+1]-s[1])*a[1]);return math.identityMat3(e),math.translationMat3v(s,e),math.identityMat3(t),math.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t),{quantized:o,decodeMatrix:math.mulMat3(e,t,math.identityMat3())}}}();function compressNormals(e){const t=new Int8Array(e.length);let i,s,r,o,a;for(let n=0;n<e.length;n+=3)r=i=octEncodeVec3(e,n,"floor","floor"),o=a=dot(e,n,s=octDecodeVec2(i)),(o=dot(e,n,s=octDecodeVec2(i=octEncodeVec3(e,n,"ceil","floor"))))>a&&(r=i,a=o),(o=dot(e,n,s=octDecodeVec2(i=octEncodeVec3(e,n,"floor","ceil"))))>a&&(r=i,a=o),(o=dot(e,n,s=octDecodeVec2(i=octEncodeVec3(e,n,"ceil","ceil"))))>a&&(r=i,a=o),t[n]=r[0],t[n+1]=r[1];return t}function octEncodeVec3(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 octDecodeVec2(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 dot(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}function decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]}function 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}function decompressNormal(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}function decompressNormals(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 a=1-Math.abs(r)-Math.abs(o);a<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t}const geometryCompressionUtils={getPositionsBounds:getPositionsBounds,compressPositions:compressPositions,decompressPositions:decompressPositions,decompressPosition:decompressPosition,decompressAABB:decompressAABB,getUVBounds:getUVBounds,compressUVs:compressUVs,decompressUVs:decompressUVs,decompressUV:decompressUV,compressNormals:compressNormals,decompressNormals:decompressNormals,decompressNormal:decompressNormal},memoryStats=stats.memory,bigIndicesSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,IndexArrayType=bigIndicesSupported?Uint32Array:Uint16Array,tempAABB=math.AABB3();class ReadableGeometry extends Geometry{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new RenderState({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=geometryCompressionUtils.getPositionsBounds(t.positions),s=geometryCompressionUtils.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=geometryCompressionUtils.getUVBounds(t.uv),s=geometryCompressionUtils.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);if(t.normals&&(this._state.compressGeometry?i.normals=geometryCompressionUtils.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices){if(!bigIndicesSupported&&t.indices.constructor===Uint32Array)return void this.error("This WebGL implementation does not support Uint32Array");i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new IndexArrayType(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),memoryStats.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),memoryStats.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),memoryStats.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),memoryStats.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),memoryStats.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ArrayBuf(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),memoryStats.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=buildEdgeIndices(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),memoryStats.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=math.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),memoryStats.positions+=this._pickTrianglePositionsBuf.numItems,memoryStats.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),geometryCompressionUtils.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=geometryCompressionUtils.getPositionsBounds(e),s=geometryCompressionUtils.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),geometryCompressionUtils.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),geometryCompressionUtils.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=math.AABB3()),math.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=math.OBB3()),math.positions3ToAABB3(this._state.positions,tempAABB,this._state.positionsDecodeMatrix),math.AABB3ToOBB3(tempAABB,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),memoryStats.meshes--}}class Material extends Component{get type(){return"Material"}constructor(e,t={}){super(e,t),stats.memory.materials++}destroy(){super.destroy(),stats.memory.materials--}}const alphaModes={opaque:0,mask:1,blend:2},alphaModeNames=["opaque","mask","blend"];class PhongMaterial extends Material{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new RenderState({type:"PhongMaterial",ambient:math.vec3([1,1,1]),diffuse:math.vec3([1,1,1]),specular:math.vec3([1,1,1]),emissive:math.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=void 0!==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=alphaModes[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 alphaModeNames[this._state.alphaMode]}set alphaCutoff(e){null!==e&&void 0!==e||(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const PRESETS={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:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],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 EmphasisMaterial extends Material{get type(){return"EmphasisMaterial"}get presets(){return PRESETS}constructor(e,t={}){super(e,t),this._state=new RenderState({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!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)):(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)}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=void 0!==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=void 0!==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 preset(e){if(e=e||"default",this._preset===e)return;const t=PRESETS[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._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(PRESETS).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const angleAxis=new Float32Array(4),q1=new Float32Array(4),q2=new Float32Array(4),xAxis=new Float32Array([1,0,0]),yAxis=new Float32Array([0,1,0]),zAxis=new Float32Array([0,0,1]),veca=new Float32Array(3),vecb=new Float32Array(3),identityMat=math.identityMat4();class Node extends Component{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=math.vec3(),this._quaternion=math.identityQuaternion(),this._rotation=math.vec3(),this._position=math.vec3(),this._localMatrix=math.identityMat4(),this._worldMatrix=math.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.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,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}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))[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))[0]=1,t[1]=1,t[2]=1),t[3]=null!==e&&void 0!==e?e:1;for(let t=0,i=this._children.length;t<i;t++)this._children[t].opacity=e}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}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)math.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=math.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;math.collapseAABB3(this._aabb);for(let t=0,i=this._children.length;t<i;t++)(e=this._children[t]).collidable&&math.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(utils.isNumeric(e)||utils.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+utils.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)}}e.id;if(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._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])._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(utils.isNumeric(e)||utils.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+utils.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]),math.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]),math.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=math.identityMat4()),this._localMatrix.set(e||identityMat),math.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=math.identityMat4()),math.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 angleAxis[0]=e[0],angleAxis[1]=e[1],angleAxis[2]=e[2],angleAxis[3]=t*math.DEGTORAD,math.angleAxisToQuaternion(angleAxis,q1),math.mulQuaternions(this.quaternion,q1,q2),this.quaternion=q2,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return angleAxis[0]=e[0],angleAxis[1]=e[1],angleAxis[2]=e[2],angleAxis[3]=t*math.DEGTORAD,math.angleAxisToQuaternion(angleAxis,q1),math.mulQuaternions(q1,this.quaternion,q1),this}rotateX(e){return this.rotate(xAxis,e)}rotateY(e){return this.rotate(yAxis,e)}rotateZ(e){return this.rotate(zAxis,e)}translate(e,t){return math.vec3ApplyQuaternion(this.quaternion,e,veca),math.mulVec3Scalar(veca,t,vecb),math.addVec3(this.position,vecb,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(xAxis,e)}translateY(e){return this.translate(yAxis,e)}translateZ(e){return this.translate(zAxis,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),this._xrayed&&this.scene._objectXRayedUpdated(this,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1),this._isObject)){const e=!1;this.scene._objectColorizeUpdated(this,e)}if(this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i<s;i++)(t=e[i]).destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}const DrawShaderSource=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=buildVertexLambert(e),this.fragment=buildFragmentLambert(e)):(this.vertex=buildVertexDraw(e),this.fragment=buildFragmentDraw(e))},TEXTURE_DECODE_FUNCS={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"};function getReceivesShadow(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 hasTextures(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)}function hasNormals(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}function getFragmentFloatPrecision(e){return e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?"highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp":"mediump"}function buildVertexLambert(e){const t=e.scene._sectionPlanesState,i=e.scene._lightsState,s=e._geometry._state,r=e._state.billboard,o=e._state.stationary,a=t.sectionPlanes.length>0,n=!!s.compressGeometry;let l,h,c;const d=[];if(d.push("// Lambertian drawing vertex shader"),d.push("attribute vec3 position;"),d.push("uniform mat4 modelMatrix;"),d.push("uniform mat4 viewMatrix;"),d.push("uniform mat4 projMatrix;"),d.push("uniform vec4 colorize;"),n&&d.push("uniform mat4 positionsDecodeMatrix;"),a&&d.push("varying vec4 vWorldPosition;"),d.push("uniform vec4 lightAmbient;"),d.push("uniform vec4 materialColor;"),d.push("uniform vec3 materialEmissive;"),s.normalsBuf){for(d.push("attribute vec3 normal;"),d.push("uniform mat4 modelNormalMatrix;"),d.push("uniform mat4 viewNormalMatrix;"),l=0,h=i.lights.length;l<h;l++)"ambient"!==(c=i.lights[l]).type&&(d.push("uniform vec4 lightColor"+l+";"),"dir"===c.type&&d.push("uniform vec3 lightDir"+l+";"),"point"===c.type&&d.push("uniform vec3 lightPos"+l+";"),"spot"===c.type&&(d.push("uniform vec3 lightPos"+l+";"),d.push("uniform vec3 lightDir"+l+";")));n&&(d.push("vec3 octDecode(vec2 oct) {"),d.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),d.push("    if (v.z < 0.0) {"),d.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);"),d.push("    }"),d.push("    return normalize(v);"),d.push("}"))}if(d.push("varying vec4 vColor;"),"points"===s.primitiveName&&d.push("uniform float pointSize;"),"spherical"!==r&&"cylindrical"!==r||(d.push("void billboard(inout mat4 mat) {"),d.push("   mat[0][0] = 1.0;"),d.push("   mat[0][1] = 0.0;"),d.push("   mat[0][2] = 0.0;"),"spherical"===r&&(d.push("   mat[1][0] = 0.0;"),d.push("   mat[1][1] = 1.0;"),d.push("   mat[1][2] = 0.0;")),d.push("   mat[2][0] = 0.0;"),d.push("   mat[2][1] = 0.0;"),d.push("   mat[2][2] =1.0;"),d.push("}")),d.push("void main(void) {"),d.push("vec4 localPosition = vec4(position, 1.0); "),d.push("vec4 worldPosition;"),n&&d.push("localPosition = positionsDecodeMatrix * localPosition;"),s.normalsBuf&&(n?d.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):d.push("vec4 localNormal = vec4(normal, 0.0); "),d.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),d.push("mat4 viewNormalMatrix2 = viewNormalMatrix;")),d.push("mat4 viewMatrix2 = viewMatrix;"),d.push("mat4 modelMatrix2 = modelMatrix;"),o&&d.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===r||"cylindrical"===r?(d.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),d.push("billboard(modelMatrix2);"),d.push("billboard(viewMatrix2);"),d.push("billboard(modelViewMatrix);"),s.normalsBuf&&(d.push("mat4 modelViewNormalMatrix =  viewNormalMatrix2 * modelNormalMatrix2;"),d.push("billboard(modelNormalMatrix2);"),d.push("billboard(viewNormalMatrix2);"),d.push("billboard(modelViewNormalMatrix);")),d.push("worldPosition = modelMatrix2 * localPosition;"),d.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(d.push("worldPosition = modelMatrix2 * localPosition;"),d.push("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),s.normalsBuf&&d.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);"),d.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),d.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),d.push("float lambertian = 1.0;"),s.normalsBuf)for(l=0,h=i.lights.length;l<h;l++)if("ambient"!==(c=i.lights[l]).type){if("dir"===c.type)"view"===c.space?d.push("viewLightDir = normalize(lightDir"+l+");"):d.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+l+", 0.0)).xyz);");else if("point"===c.type)"view"===c.space?d.push("viewLightDir = normalize(lightPos"+l+" - viewPosition.xyz);"):d.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+l+", 0.0)).xyz);");else{if("spot"!==c.type)continue;"view"===c.space?d.push("viewLightDir = normalize(lightDir"+l+");"):d.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+l+", 0.0)).xyz);")}d.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),d.push("reflectedColor += lambertian * (lightColor"+l+".rgb * lightColor"+l+".a);")}return d.push("vColor = vec4(materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),a&&d.push("vWorldPosition = worldPosition;"),"points"===s.primitiveName&&d.push("gl_PointSize = pointSize;"),d.push("   gl_Position = projMatrix * viewPosition;"),d.push("}"),d}function buildFragmentLambert(e){const t=e.scene,i=t._sectionPlanesState,s=(e._material._state,e._geometry._state);let r,o;const a=i.sectionPlanes.length>0,n=t.gammaOutput,l=[];if(l.push("// Lambertian drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),a)for(l.push("varying vec4 vWorldPosition;"),l.push("uniform bool clippable;"),r=0,o=i.sectionPlanes.length;r<o;r++)l.push("uniform bool sectionPlaneActive"+r+";"),l.push("uniform vec3 sectionPlanePos"+r+";"),l.push("uniform vec3 sectionPlaneDir"+r+";");if(l.push("varying vec4 vColor;"),n&&(l.push("uniform float gammaFactor;"),l.push("    vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),l.push("    return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),l.push("}")),l.push("void main(void) {"),a){for(l.push("if (clippable) {"),l.push("  float dist = 0.0;"),r=0,o=i.sectionPlanes.length;r<o;r++)l.push("if (sectionPlaneActive"+r+") {"),l.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),l.push("}");l.push("  if (dist > 0.0) { discard; }"),l.push("}")}return"points"===s.primitiveName&&(l.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),l.push("float r = dot(cxy, cxy);"),l.push("if (r > 1.0) {"),l.push("   discard;"),l.push("}")),n?l.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):l.push("gl_FragColor = vColor;"),l.push("}"),l}function buildVertexDraw(e){const t=e.scene,i=e._material,s=e._state,r=t._sectionPlanesState,o=e._geometry._state,a=t._lightsState;let n,l,h;const c=s.billboard,d=s.stationary,u=hasTextures(e),p=hasNormals(e),m=r.sectionPlanes.length>0,_=getReceivesShadow(e),g=!!o.compressGeometry,f=[];if(p&&i._normalMap&&f.push("#extension GL_OES_standard_derivatives : enable"),f.push("// Drawing vertex shader"),f.push("attribute  vec3 position;"),g&&f.push("uniform mat4 positionsDecodeMatrix;"),f.push("uniform  mat4 modelMatrix;"),f.push("uniform  mat4 viewMatrix;"),f.push("uniform  mat4 projMatrix;"),f.push("varying  vec3 vViewPosition;"),m&&f.push("varying vec4 vWorldPosition;"),a.lightMaps.length>0&&f.push("varying    vec3 vWorldNormal;"),p){for(f.push("attribute  vec3 normal;"),f.push("uniform    mat4 modelNormalMatrix;"),f.push("uniform    mat4 viewNormalMatrix;"),f.push("varying    vec3 vViewNormal;"),n=0,l=a.lights.length;n<l;n++)"ambient"!==(h=a.lights[n]).type&&("dir"===h.type&&f.push("uniform vec3 lightDir"+n+";"),"point"===h.type&&f.push("uniform vec3 lightPos"+n+";"),"spot"===h.type&&(f.push("uniform vec3 lightPos"+n+";"),f.push("uniform vec3 lightDir"+n+";")),"dir"===h.type&&"view"===h.space||f.push("varying vec4 vViewLightReverseDirAndDist"+n+";"));g&&(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("}"))}if(u&&(f.push("attribute vec2 uv;"),f.push("varying vec2 vUV;"),g&&f.push("uniform mat3 uvDecodeMatrix;")),o.colors&&(f.push("attribute vec4 color;"),f.push("varying vec4 vColor;")),"points"===o.primitiveName&&f.push("uniform float pointSize;"),"spherical"!==c&&"cylindrical"!==c||(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"===c&&(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("}")),_)for(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);"),n=0,l=a.lights.length;n<l;n++)a.lights[n].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+n+";"),f.push("uniform mat4 shadowProjMatrix"+n+";"),f.push("varying vec4 vShadowPosFromLight"+n+";"));if(f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),g&&f.push("localPosition = positionsDecodeMatrix * localPosition;"),p&&(g?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;"),d&&f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===c||"cylindrical"===c?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),p&&(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("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),p)for(f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.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;"),n=0,l=a.lights.length;n<l;n++)"ambient"!==(h=a.lights[n]).type&&("dir"===h.type&&"world"===h.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+n+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+n+" = vec4(-tmpVec3, 0.0);")),"point"===h.type&&("world"===h.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+n+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+n+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+n+" = vec4(tmpVec3, lightDist);")));if(u&&(g?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;")),o.colors&&f.push("vColor = color;"),"points"===o.primitiveName&&f.push("gl_PointSize = pointSize;"),m&&f.push("vWorldPosition = worldPosition;"),f.push("   vViewPosition = viewPosition.xyz;"),f.push("   gl_Position = projMatrix * viewPosition;"),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(f.push("vec4 tempx; "),n=0,l=a.lights.length;n<l;n++)a.lights[n].castsShadow&&f.push("vShadowPosFromLight"+n+" = texUnitConverter * shadowProjMatrix"+n+" * (shadowViewMatrix"+n+" * worldPosition); ");return f.push("}"),f}function buildFragmentDraw(e){const t=e.scene,i=t.canvas.gl,s=e._material,r=e._geometry._state,o=e.scene._sectionPlanesState,a=e.scene._lightsState,n=e._material._state,l=o.sectionPlanes.length>0,h=hasNormals(e),c=r.uvBuf,d="PhongMaterial"===n.type,u="MetallicMaterial"===n.type,p="SpecularMaterial"===n.type,m=getReceivesShadow(e),_=(t.gammaInput,t.gammaOutput);let g,f;const v=[];if(v.push("// Drawing fragment shader"),h&&s._normalMap&&v.push("#extension GL_OES_standard_derivatives : enable"),v.push("precision "+getFragmentFloatPrecision(i)+" float;"),m&&(v.push("float unpackDepth (vec4 color) {"),v.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));"),v.push("  return dot(color, bitShift);"),v.push("}")),v.push("uniform float gammaFactor;"),v.push("vec4 linearToLinear( in vec4 value ) {"),v.push("  return value;"),v.push("}"),v.push("vec4 sRGBToLinear( in vec4 value ) {"),v.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 );"),v.push("}"),v.push("vec4 gammaToLinear( in vec4 value) {"),v.push("  return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),v.push("}"),_&&(v.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),v.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),v.push("}")),l){v.push("varying vec4 vWorldPosition;"),v.push("uniform bool clippable;");for(var b=0;b<o.sectionPlanes.length;b++)v.push("uniform bool sectionPlaneActive"+b+";"),v.push("uniform vec3 sectionPlanePos"+b+";"),v.push("uniform vec3 sectionPlaneDir"+b+";")}if(h&&(a.lightMaps.length>0&&(v.push("uniform samplerCube lightMap;"),v.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&v.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("uniform mat4 viewMatrix;"),v.push("#define PI 3.14159265359"),v.push("#define RECIPROCAL_PI 0.31830988618"),v.push("#define RECIPROCAL_PI2 0.15915494"),v.push("#define EPSILON 1e-6"),v.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),v.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),v.push("   return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),v.push("}"),v.push("struct IncidentLight {"),v.push("   vec3 color;"),v.push("   vec3 direction;"),v.push("};"),v.push("struct ReflectedLight {"),v.push("   vec3 diffuse;"),v.push("   vec3 specular;"),v.push("};"),v.push("struct Geometry {"),v.push("   vec3 position;"),v.push("   vec3 viewNormal;"),v.push("   vec3 worldNormal;"),v.push("   vec3 viewEyeDir;"),v.push("};"),v.push("struct Material {"),v.push("   vec3    diffuseColor;"),v.push("   float   specularRoughness;"),v.push("   vec3    specularColor;"),v.push("   float   shine;"),v.push("};"),d&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(v.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(v.push("   vec3 irradiance = "+TEXTURE_DECODE_FUNCS[a.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),v.push("   irradiance *= PI;"),v.push("   vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),v.push("   reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(v.push("   vec3 reflectVec             = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),v.push("   vec3 radiance               = textureCube(reflectionMap, reflectVec).rgb * 0.2;"),v.push("   reflectedLight.specular     += radiance;")),v.push("}")),v.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),v.push("   float dotNL     = saturate(dot(geometry.viewNormal, directLight.direction));"),v.push("   vec3 irradiance = dotNL * directLight.color * PI;"),v.push("   reflectedLight.diffuse  += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),v.push("   reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),v.push("}")),(u||p)&&(v.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),v.push("   float r = ggxRoughness + 0.0001;"),v.push("   return (2.0 / (r * r) - 2.0);"),v.push("}"),v.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),v.push("   float maxMIPLevelScalar = float( maxMIPLevel );"),v.push("   float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),v.push("   return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),v.push("}"),a.reflectionMaps.length>0&&(v.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),v.push("   float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),v.push("   vec3 envMapColor = "+TEXTURE_DECODE_FUNCS[a.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),v.push("  return envMapColor;"),v.push("}")),v.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),v.push("   float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),v.push("   return ( 1.0 - specularColor ) * fresnel + specularColor;"),v.push("}"),v.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),v.push("   float a2 = ( alpha * alpha );"),v.push("   float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),v.push("   float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),v.push("   return 1.0 / ( gl * gv );"),v.push("}"),v.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),v.push("   float a2 = ( alpha * alpha );"),v.push("   float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),v.push("   float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),v.push("   return 0.5 / max( gv + gl, EPSILON );"),v.push("}"),v.push("float D_GGX(const in float alpha, const in float dotNH) {"),v.push("   float a2 = ( alpha * alpha );"),v.push("   float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),v.push("   return RECIPROCAL_PI * a2 / ( denom * denom);"),v.push("}"),v.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),v.push("   float alpha = ( roughness * roughness );"),v.push("   vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),v.push("   float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),v.push("   float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),v.push("   float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),v.push("   float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),v.push("   vec3  F = F_Schlick( specularColor, dotLH );"),v.push("   float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),v.push("   float D = D_GGX( alpha, dotNH );"),v.push("   return F * (G * D);"),v.push("}"),v.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),v.push("   float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),v.push("   const vec4 c0 = vec4( -1, -0.0275, -0.572,  0.022);"),v.push("   const vec4 c1 = vec4(  1,  0.0425,   1.04, -0.04);"),v.push("   vec4 r = roughness * c0 + c1;"),v.push("   float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),v.push("   vec2 AB    = vec2(-1.04, 1.04) * a004 + r.zw;"),v.push("   return specularColor * AB.x + AB.y;"),v.push("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(v.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(v.push("   vec3 irradiance = sRGBToLinear(textureCube(lightMap, geometry.worldNormal)).rgb;"),v.push("   irradiance *= PI;"),v.push("   vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),v.push("   reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(v.push("   vec3 reflectVec             = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),v.push("   reflectVec                  = inverseTransformDirection(reflectVec, viewMatrix);"),v.push("   float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),v.push("   vec3 radiance               = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),v.push("   vec3 specularBRDFContrib    = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),v.push("   reflectedLight.specular     += radiance * specularBRDFContrib;")),v.push("}")),v.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),v.push("   float dotNL     = saturate(dot(geometry.viewNormal, incidentLight.direction));"),v.push("   vec3 irradiance = dotNL * incidentLight.color * PI;"),v.push("   reflectedLight.diffuse  += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),v.push("   reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),v.push("}"))),v.push("varying vec3 vViewPosition;"),r.colors&&v.push("varying vec4 vColor;"),c&&(h&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&v.push("varying vec2 vUV;"),h&&(a.lightMaps.length>0&&v.push("varying vec3 vWorldNormal;"),v.push("varying vec3 vViewNormal;")),n.ambient&&v.push("uniform vec3 materialAmbient;"),n.baseColor&&v.push("uniform vec3 materialBaseColor;"),void 0!==n.alpha&&null!==n.alpha&&v.push("uniform vec4 materialAlphaModeCutoff;"),n.emissive&&v.push("uniform vec3 materialEmissive;"),n.diffuse&&v.push("uniform vec3 materialDiffuse;"),void 0!==n.glossiness&&null!==n.glossiness&&v.push("uniform float materialGlossiness;"),void 0!==n.shininess&&null!==n.shininess&&v.push("uniform float materialShininess;"),n.specular&&v.push("uniform vec3 materialSpecular;"),void 0!==n.metallic&&null!==n.metallic&&v.push("uniform float materialMetallic;"),void 0!==n.roughness&&null!==n.roughness&&v.push("uniform float materialRoughness;"),void 0!==n.specularF0&&null!==n.specularF0&&v.push("uniform float materialSpecularF0;"),c&&s._ambientMap&&(v.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&v.push("uniform mat4 ambientMapMatrix;")),c&&s._baseColorMap&&(v.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&v.push("uniform mat4 baseColorMapMatrix;")),c&&s._diffuseMap&&(v.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&v.push("uniform mat4 diffuseMapMatrix;")),c&&s._emissiveMap&&(v.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&v.push("uniform mat4 emissiveMapMatrix;")),h&&c&&s._metallicMap&&(v.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&v.push("uniform mat4 metallicMapMatrix;")),h&&c&&s._roughnessMap&&(v.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&v.push("uniform mat4 roughnessMapMatrix;")),h&&c&&s._metallicRoughnessMap&&(v.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&v.push("uniform mat4 metallicRoughnessMapMatrix;")),h&&s._normalMap&&(v.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&v.push("uniform mat4 normalMapMatrix;"),v.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),v.push("      vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),v.push("      vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),v.push("      vec2 st0 = dFdx( uv.st );"),v.push("      vec2 st1 = dFdy( uv.st );"),v.push("      vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),v.push("      vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),v.push("      vec3 N = normalize( surf_norm );"),v.push("      vec3 mapN = texture2D( normalMap, uv ).xyz * 2.0 - 1.0;"),v.push("      mat3 tsn = mat3( S, T, N );"),v.push("      return normalize( tsn * mapN );"),v.push("}")),c&&s._occlusionMap&&(v.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&v.push("uniform mat4 occlusionMapMatrix;")),c&&s._alphaMap&&(v.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&v.push("uniform mat4 alphaMapMatrix;")),h&&c&&s._specularMap&&(v.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&v.push("uniform mat4 specularMapMatrix;")),h&&c&&s._glossinessMap&&(v.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&v.push("uniform mat4 glossinessMapMatrix;")),h&&c&&s._specularGlossinessMap&&(v.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&v.push("uniform mat4 materialSpecularGlossinessMapMatrix;")),h&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(v.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),v.push("    float fr = abs(dot(eyeDir, normal));"),v.push("    float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),v.push("    return pow(finalFr, power);"),v.push("}"),s._diffuseFresnel&&(v.push("uniform float  diffuseFresnelCenterBias;"),v.push("uniform float  diffuseFresnelEdgeBias;"),v.push("uniform float  diffuseFresnelPower;"),v.push("uniform vec3   diffuseFresnelCenterColor;"),v.push("uniform vec3   diffuseFresnelEdgeColor;")),s._specularFresnel&&(v.push("uniform float  specularFresnelCenterBias;"),v.push("uniform float  specularFresnelEdgeBias;"),v.push("uniform float  specularFresnelPower;"),v.push("uniform vec3   specularFresnelCenterColor;"),v.push("uniform vec3   specularFresnelEdgeColor;")),s._alphaFresnel&&(v.push("uniform float  alphaFresnelCenterBias;"),v.push("uniform float  alphaFresnelEdgeBias;"),v.push("uniform float  alphaFresnelPower;"),v.push("uniform vec3   alphaFresnelCenterColor;"),v.push("uniform vec3   alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(v.push("uniform float  materialSpecularF0FresnelCenterBias;"),v.push("uniform float  materialSpecularF0FresnelEdgeBias;"),v.push("uniform float  materialSpecularF0FresnelPower;"),v.push("uniform vec3   materialSpecularF0FresnelCenterColor;"),v.push("uniform vec3   materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(v.push("uniform float  emissiveFresnelCenterBias;"),v.push("uniform float  emissiveFresnelEdgeBias;"),v.push("uniform float  emissiveFresnelPower;"),v.push("uniform vec3   emissiveFresnelCenterColor;"),v.push("uniform vec3   emissiveFresnelEdgeColor;"))),v.push("uniform vec4   lightAmbient;"),h)for(b=0,g=a.lights.length;b<g;b++)"ambient"!==(f=a.lights[b]).type&&(v.push("uniform vec4 lightColor"+b+";"),"point"===f.type&&v.push("uniform vec3 lightAttenuation"+b+";"),"dir"===f.type&&"view"===f.space&&v.push("uniform vec3 lightDir"+b+";"),"point"===f.type&&"view"===f.space?v.push("uniform vec3 lightPos"+b+";"):v.push("varying vec4 vViewLightReverseDirAndDist"+b+";"));if(m)for(b=0,g=a.lights.length;b<g;b++)a.lights[b].castsShadow&&(v.push("varying vec4 vShadowPosFromLight"+b+";"),v.push("uniform sampler2D shadowMap"+b+";"));if(v.push("uniform vec4 colorize;"),v.push("void main(void) {"),l){v.push("if (clippable) {"),v.push("  float dist = 0.0;");for(b=0;b<o.sectionPlanes.length;b++)v.push("if (sectionPlaneActive"+b+") {"),v.push("   dist += clamp(dot(-sectionPlaneDir"+b+".xyz, vWorldPosition.xyz - sectionPlanePos"+b+".xyz), 0.0, 1000.0);"),v.push("}");v.push("  if (dist > 0.0) { discard; }"),v.push("}")}if("points"===r.primitiveName&&(v.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),v.push("float r = dot(cxy, cxy);"),v.push("if (r > 1.0) {"),v.push("   discard;"),v.push("}")),v.push("float occlusion = 1.0;"),n.ambient?v.push("vec3 ambientColor = materialAmbient;"):v.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);"),n.diffuse?v.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?v.push("vec3 diffuseColor = materialBaseColor;"):v.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);"),r.colors&&v.push("diffuseColor *= vColor.rgb;"),n.emissive?v.push("vec3 emissiveColor = materialEmissive;"):v.push("vec3  emissiveColor = vec3(0.0, 0.0, 0.0);"),n.specular?v.push("vec3 specular = materialSpecular;"):v.push("vec3 specular = vec3(1.0, 1.0, 1.0);"),void 0!==n.alpha?v.push("float alpha = materialAlphaModeCutoff[0];"):v.push("float alpha = 1.0;"),r.colors&&v.push("alpha *= vColor.a;"),void 0!==n.glossiness?v.push("float glossiness = materialGlossiness;"):v.push("float glossiness = 1.0;"),void 0!==n.metallic?v.push("float metallic = materialMetallic;"):v.push("float metallic = 1.0;"),void 0!==n.roughness?v.push("float roughness = materialRoughness;"):v.push("float roughness = 1.0;"),void 0!==n.specularF0?v.push("float specularF0 = materialSpecularF0;"):v.push("float specularF0 = 1.0;"),c&&(h&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(v.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),v.push("vec2 textureCoord;")),c&&s._ambientMap&&(s._ambientMap._state.matrix?v.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 ambientTexel = texture2D(ambientMap, textureCoord).rgb;"),v.push("ambientTexel = "+TEXTURE_DECODE_FUNCS[s._ambientMap._state.encoding]+"(ambientTexel);"),v.push("ambientColor *= ambientTexel.rgb;")),c&&s._diffuseMap&&(s._diffuseMap._state.matrix?v.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 diffuseTexel = texture2D(diffuseMap, textureCoord);"),v.push("diffuseTexel = "+TEXTURE_DECODE_FUNCS[s._diffuseMap._state.encoding]+"(diffuseTexel);"),v.push("diffuseColor *= diffuseTexel.rgb;"),v.push("alpha *= diffuseTexel.a;")),c&&s._baseColorMap&&(s._baseColorMap._state.matrix?v.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 baseColorTexel = texture2D(baseColorMap, textureCoord);"),v.push("baseColorTexel = "+TEXTURE_DECODE_FUNCS[s._baseColorMap._state.encoding]+"(baseColorTexel);"),v.push("diffuseColor *= baseColorTexel.rgb;"),v.push("alpha *= baseColorTexel.a;")),c&&s._emissiveMap&&(s._emissiveMap._state.matrix?v.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 emissiveTexel = texture2D(emissiveMap, textureCoord);"),v.push("emissiveTexel = "+TEXTURE_DECODE_FUNCS[s._emissiveMap._state.encoding]+"(emissiveTexel);"),v.push("emissiveColor *= emissiveTexel.rgb;")),c&&s._alphaMap&&(s._alphaMap._state.matrix?v.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("alpha *= texture2D(alphaMap, textureCoord).r;")),c&&s._occlusionMap&&(s._occlusionMap._state.matrix?v.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("occlusion *= texture2D(occlusionMap, textureCoord).r;")),h&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){for(c&&s._normalMap?(s._normalMap._state.matrix?v.push("textureCoord = (normalMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):v.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?v.push("textureCoord = (specularMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("specular *= texture2D(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?v.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("glossiness *= texture2D(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?v.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec4 specGlossRGB = texture2D(materialSpecularGlossinessMap, textureCoord).rgba;"),v.push("specular *= specGlossRGB.rgb;"),v.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?v.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("metallic *= texture2D(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?v.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("roughness *= texture2D(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?v.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):v.push("textureCoord = texturePos.xy;"),v.push("vec3 metalRoughRGB = texture2D(metallicRoughnessMap, textureCoord).rgb;"),v.push("metallic *= metalRoughRGB.b;"),v.push("roughness *= metalRoughRGB.g;")),v.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(v.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),v.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(v.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),v.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(v.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),v.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(v.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),v.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),v.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),v.push("   discard;"),v.push("}"),v.push("IncidentLight  light;"),v.push("Material       material;"),v.push("Geometry       geometry;"),v.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),v.push("vec3           viewLightDir;"),d&&(v.push("material.diffuseColor      = diffuseColor;"),v.push("material.specularColor     = specular;"),v.push("material.shine             = materialShininess;")),p&&(v.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),v.push("material.diffuseColor      = diffuseColor * oneMinusSpecularStrength;"),v.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),v.push("material.specularColor     = specular;")),u&&(v.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),v.push("material.diffuseColor      = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),v.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),v.push("material.specularColor     = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),v.push("geometry.position      = vViewPosition;"),a.lightMaps.length>0&&v.push("geometry.worldNormal   = normalize(vWorldNormal);"),v.push("geometry.viewNormal    = viewNormal;"),v.push("geometry.viewEyeDir    = viewEyeDir;"),d&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||u)&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&v.push("computePBRLightMapping(geometry, material, reflectedLight);"),v.push("float shadow = 1.0;"),v.push("float shadowAcneRemover = 0.007;"),v.push("vec3 fragmentDepth;"),v.push("float texelSize = 1.0 / 1024.0;"),v.push("float amountInLight = 0.0;"),v.push("vec3 shadowCoord;"),v.push("vec4 rgbaDepth;"),v.push("float depth;"),b=0,g=a.lights.length;b<g;b++)"ambient"!==(f=a.lights[b]).type&&("dir"===f.type&&"view"===f.space?v.push("viewLightDir = -normalize(lightDir"+b+");"):"point"===f.type&&"view"===f.space?v.push("viewLightDir = normalize(lightPos"+b+" - vViewPosition);"):v.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+b+".xyz);"),m&&f.castsShadow?(v.push("shadow = 0.0;"),v.push("fragmentDepth = vShadowPosFromLight"+b+".xyz;"),v.push("fragmentDepth.z -= shadowAcneRemover;"),v.push("for (int x = -3; x <= 3; x++) {"),v.push("  for (int y = -3; y <= 3; y++) {"),v.push("      float texelDepth = unpackDepth(texture2D(shadowMap"+b+", fragmentDepth.xy + vec2(x, y) * texelSize));"),v.push("      if (fragmentDepth.z < texelDepth) {"),v.push("          shadow += 1.0;"),v.push("      }"),v.push("  }"),v.push("}"),v.push("shadow = shadow / 9.0;"),v.push("light.color =  lightColor"+b+".rgb * (lightColor"+b+".a * shadow);")):v.push("light.color =  lightColor"+b+".rgb * (lightColor"+b+".a );"),v.push("light.direction = viewLightDir;"),d&&v.push("computePhongLighting(light, geometry, material, reflectedLight);"),(p||u)&&v.push("computePBRLighting(light, geometry, material, reflectedLight);"));d?(v.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),v.push("vec3 outgoingLight =  ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;")):v.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else v.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),v.push("vec3 outgoingLight = emissiveColor + ambientColor;");return v.push("gl_FragColor = vec4(outgoingLight, alpha) * colorize;"),_&&v.push("gl_FragColor = linearToGamma(gl_FragColor, gammaFactor);"),v.push("}"),v}class Shader{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 Sampler{constructor(e,t){this.bindTexture=function(i,s){return!!i.bind(s)&&(e.uniform1i(t,s),!0)}}}class Attribute{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 ids$1=new Map({});function joinSansComments(e){const t=[];let i,s;for(let r=0,o=e.length;r<o;r++)(s=(i=e[r]).indexOf("/"))>0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function logErrors(e){console.error(e.join("\n"))}class Program{constructor(e,t){this.id=ids$1.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 Shader(e,e.VERTEX_SHADER,joinSansComments(this.source.vertex)),this._fragmentShader=new Shader(e,e.FRAGMENT_SHADER,joinSansComments(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void logErrors(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void logErrors(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void logErrors(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void logErrors(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 logErrors(this.errors);const a=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<a;++i)(s=e.getActiveUniform(this.handle,i))&&("\0"===(r=s.name)[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?this.samplers[r]=new Sampler(e,o):this.uniforms[r]=o);const n=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<n;i++)(t=e.getActiveAttrib(this.handle,i))&&(o=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new Attribute(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&&(ids$1.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 ids$2=new Map({}),DrawRenderer=function(e,t){this.id=ids$2.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new DrawShaderSource(t),this._allocate(t)},drawRenderers={};DrawRenderer.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=drawRenderers[i];if(!s){if((s=new DrawRenderer(i,e)).errors)return console.log(s.errors.join("\n")),null;drawRenderers[i]=s,stats.memory.programs++}return s._useCount++,s},DrawRenderer.prototype.put=function(){0==--this._useCount&&(ids$2.removeItem(this.id),this._program&&this._program.destroy(),delete drawRenderers[this._hash],stats.memory.programs--)},DrawRenderer.prototype.webglContextRestored=function(){this._program=null},DrawRenderer.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=WEBGL_INFO.MAX_TEXTURE_UNITS,s=t.scene,r=t._material,o=s.canvas.gl,a=this._program,n=t._state,l=t._material._state,h=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),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&&(a.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&&(a.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&&(a.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&&(a.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&&(a.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&&(a.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&&(a.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&&(a.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&&(a.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 n=r._metallicMap;n&&n._state.texture&&this._uMetallicMap&&(a.bindTexture(this._uMetallicMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicMapMatrix&&o.uniformMatrix4fv(this._uMetallicMapMatrix,!1,n._state.matrix));const h=r._roughnessMap;h&&h._state.texture&&this._uRoughnessMap&&(a.bindTexture(this._uRoughnessMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uRoughnessMapMatrix&&o.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,h._state.matrix));const m=r._metallicRoughnessMap;m&&m._state.texture&&this._uMetallicRoughnessMap&&(a.bindTexture(this._uMetallicRoughnessMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&o.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,m._state.matrix)),(c=r._emissiveMap)&&c._state.texture&&this._uEmissiveMap&&(a.bindTexture(this._uEmissiveMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,c._state.matrix)),(d=r._occlusionMap)&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(a.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(u=r._alphaMap)&&u._state.texture&&this._uAlphaMap&&(a.bindTexture(this._uAlphaMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,u._state.matrix)),(p=r._normalMap)&&p._state.texture&&this._uNormalMap&&(a.bindTexture(this._uNormalMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,p._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 _=r._diffuseMap;_&&_._state.texture&&this._uDiffuseMap&&(a.bindTexture(this._uDiffuseMap,_._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,_._state.matrix));const g=r._specularMap;g&&g._state.texture&&this._uSpecularMap&&(a.bindTexture(this._uSpecularMap,g._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,g._state.matrix));const f=r._glossinessMap;f&&f._state.texture&&this._uGlossinessMap&&(a.bindTexture(this._uGlossinessMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uGlossinessMapMatrix&&o.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,f._state.matrix));const v=r._specularGlossinessMap;var c,d,u,p;v&&v._state.texture&&this._uSpecularGlossinessMap&&(a.bindTexture(this._uSpecularGlossinessMap,v._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&o.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,v._state.matrix)),(c=r._emissiveMap)&&c._state.texture&&this._uEmissiveMap&&(a.bindTexture(this._uEmissiveMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,c._state.matrix)),(d=r._occlusionMap)&&d._state.texture&&this._uOcclusionMap&&(a.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(u=r._alphaMap)&&u._state.texture&&this._uAlphaMap&&(a.bindTexture(this._uAlphaMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,u._state.matrix)),(p=r._normalMap)&&p._state.texture&&this._uNormalMap&&(a.bindTexture(this._uNormalMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,p._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,n.clippable),this._uColorize){const e=n.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])}h.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,h.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,h.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(h.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(h.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(h.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(h.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(h.flagsBuf),e.bindArray++),h.indicesBuf?(h.indicesBuf.bind(),e.bindArray++):h.positions,this._lastGeometryId=h.id),h.indicesBuf?(o.drawElements(h.primitive,h.indicesBuf.numItems,h.indicesBuf.itemType,0),e.drawElements++):h.positions&&(o.drawArrays(o.TRIANGLES,0,h.positions.numItems),e.drawArrays++)},DrawRenderer.prototype._allocate=function(e){const t=e.scene.canvas.gl,i=e._material,s=e.scene._lightsState,r=e.scene._sectionPlanesState,o=e._material._state;if(this._program=new Program(t,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=[];const n=s.lights;let l;for(var h=0,c=n.length;h<c;h++){switch((l=n[h]).type){case"ambient":this._uLightAmbient[h]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[h]=a.getLocation("lightColor"+h),this._uLightPos[h]=null,this._uLightDir[h]=a.getLocation("lightDir"+h);break;case"point":this._uLightColor[h]=a.getLocation("lightColor"+h),this._uLightPos[h]=a.getLocation("lightPos"+h),this._uLightDir[h]=null,this._uLightAttenuation[h]=a.getLocation("lightAttenuation"+h);break;case"spot":this._uLightColor[h]=a.getLocation("lightColor"+h),this._uLightPos[h]=a.getLocation("lightPos"+h),this._uLightDir[h]=a.getLocation("lightDir"+h),this._uLightAttenuation[h]=a.getLocation("lightAttenuation"+h)}l.castsShadow&&(this._uShadowViewMatrix[h]=a.getLocation("shadowViewMatrix"+h),this._uShadowProjMatrix[h]=a.getLocation("shadowProjMatrix"+h))}s.lightMaps.length>0&&(this._uLightMap="lightMap"),s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=r.sectionPlanes.length;h<c;h++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+h),pos:a.getLocation("sectionPlanePos"+h),dir:a.getLocation("sectionPlaneDir"+h)});switch(this._uPointSize=a.getLocation("pointSize"),o.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"),i._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=a.getLocation("ambientMapMatrix")),i._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),i._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),i._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),i._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),i._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=a.getLocation("reflectivityMapMatrix")),i._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix")),i._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),i._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")),i._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")),i._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")),i._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")),i._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"),i._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=a.getLocation("baseColorMapMatrix")),i._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=a.getLocation("metallicMapMatrix")),i._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=a.getLocation("roughnessMapMatrix")),i._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=a.getLocation("metallicRoughnessMapMatrix")),i._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),i._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),i._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),i._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"),i._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),i._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),i._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=a.getLocation("glossinessMapMatrix")),i._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=a.getLocation("materialSpecularGlossinessMapMatrix")),i._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),i._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),i._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),i._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._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},DrawRenderer.prototype._bindProgram=function(e){const t=WEBGL_INFO.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=i._lightsState,o=i._sectionPlanesState;r.lights;let a;const n=this._program;n.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;const l=i.camera,h=l._state;s.uniformMatrix4fv(this._uViewMatrix,!1,h.matrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,h.normalMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,l._project._state.matrix);for(var c=0,d=r.lights.length;c<d;c++)if(a=r.lights[c],this._uLightAmbient[c])s.uniform4f(this._uLightAmbient[c],a.color[0],a.color[1],a.color[2],a.intensity);else if(this._uLightColor[c]&&s.uniform4f(this._uLightColor[c],a.color[0],a.color[1],a.color[2],a.intensity),this._uLightPos[c]&&(s.uniform3fv(this._uLightPos[c],a.pos),this._uLightAttenuation[c]&&s.uniform1f(this._uLightAttenuation[c],a.attenuation)),this._uLightDir[c]&&s.uniform3fv(this._uLightDir[c],a.dir),a.castsShadow){this._uShadowViewMatrix[c]&&s.uniformMatrix4fv(this._uShadowViewMatrix[c],!1,a.getShadowViewMatrix()),this._uShadowProjMatrix[c]&&s.uniformMatrix4fv(this._uShadowProjMatrix[c],!1,a.getShadowProjMatrix());const i=a.getShadowRenderBuf();i&&(n.bindTexture("shadowMap"+c,i.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}if(r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(n.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&&(n.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),o.sectionPlanes.length>0){const e=i._sectionPlanesState.sectionPlanes;let t,r,o,a,n;for(c=0,d=this._uSectionPlanes.length;c<d;c++)r=(t=this._uSectionPlanes[c]).active,o=e[c],r&&s.uniform1i(r,o.active),(a=t.pos)&&s.uniform3fv(t.pos,o.pos),(n=t.dir)&&s.uniform3fv(t.dir,o.dir)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class EmphasisFillShaderSource{constructor(e){this.vertex=buildVertex(e),this.fragment=buildFragment(e)}}function buildVertex(e){const t=e.scene,i=t._lightsState,s=hasNormals$1(e),r=t._sectionPlanesState.sectionPlanes.length>0,o=!!e._geometry._state.compressGeometry,a=e._state.billboard,n=e._state.stationary,l=[];let h,c,d;if(l.push("// EmphasisFillShaderSource vertex shader"),l.push("attribute vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),o&&l.push("uniform mat4 positionsDecodeMatrix;"),r&&l.push("varying vec4 vWorldPosition;"),l.push("uniform vec4   lightAmbient;"),l.push("uniform vec4   fillColor;"),s){for(l.push("attribute vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;"),h=0,c=i.lights.length;h<c;h++)"ambient"!==(d=i.lights[h]).type&&(l.push("uniform vec4 lightColor"+h+";"),"dir"===d.type&&l.push("uniform vec3 lightDir"+h+";"),"point"===d.type&&l.push("uniform vec3 lightPos"+h+";"),"spot"===d.type&&l.push("uniform vec3 lightPos"+h+";"));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("}"))}if(l.push("varying vec4 vColor;"),"spherical"!==a&&"cylindrical"!==a||(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"===a&&(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;"),n&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===a||"cylindrical"===a?(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("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);"),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(h=0,c=i.lights.length;h<c;h++)if("ambient"!==(d=i.lights[h]).type){if("dir"===d.type)"view"===d.space?l.push("viewLightDir = normalize(lightDir"+h+");"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+h+", 0.0)).xyz);");else{if("point"!==d.type)continue;"view"===d.space?l.push("viewLightDir = normalize(lightPos"+h+" - viewPosition.xyz);"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+h+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+h+".rgb * lightColor"+h+".a);")}return 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("   gl_Position = projMatrix * viewPosition;"),l.push("}"),l}function hasNormals$1(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}function buildFragment(e){const t=e.scene._sectionPlanesState,i=e.scene.gammaOutput,s=t.sectionPlanes.length>0;let r,o;const a=[];if(a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),s)for(a.push("varying vec4 vWorldPosition;"),a.push("uniform bool clippable;"),r=0,o=t.sectionPlanes.length;r<o;r++)a.push("uniform bool sectionPlaneActive"+r+";"),a.push("uniform vec3 sectionPlanePos"+r+";"),a.push("uniform vec3 sectionPlaneDir"+r+";");if(a.push("varying vec4 vColor;"),a.push("void main(void) {"),s){for(a.push("if (clippable) {"),a.push("  float dist = 0.0;"),r=0,o=t.sectionPlanes.length;r<o;r++)a.push("if (sectionPlaneActive"+r+") {"),a.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),a.push("}");a.push("  if (dist > 0.0) { discard; }"),a.push("}")}return"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push("   discard;"),a.push("}")),a.push("gl_FragColor = vColor;"),i?a.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):a.push("gl_FragColor = vColor;"),a.push("}"),a}const ids$3=new Map({}),EmphasisFillRenderer=function(e,t){this.id=ids$3.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new EmphasisFillShaderSource(t),this._allocate(t)},xrayFillRenderers={};EmphasisFillRenderer.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=xrayFillRenderers[t];return i||(i=new EmphasisFillRenderer(t,e),xrayFillRenderers[t]=i,stats.memory.programs++),i._useCount++,i},EmphasisFillRenderer.prototype.put=function(){0==--this._useCount&&(ids$3.removeItem(this.id),this._program&&this._program.destroy(),delete xrayFillRenderers[this._hash],stats.memory.programs--)},EmphasisFillRenderer.prototype.webglContextRestored=function(){this._program=null},EmphasisFillRenderer.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene.canvas.gl,r=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,o=t._state,a=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.fillColor,i=r.backfaces;e.backfaces!==i&&(i?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=i),s.uniform4f(this._uFillColor,t[0],t[1],t[2],r.fillAlpha),this._lastMaterialId=r.id}s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uModelNormalMatrix&&s.uniformMatrix4fv(this._uModelNormalMatrix,s.FALSE,t.worldNormalMatrix),this._uClippable&&s.uniform1i(this._uClippable,o.clippable),a.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,a.positionsDecodeMatrix),this._uUVDecodeMatrix&&s.uniformMatrix3fv(this._uUVDecodeMatrix,!1,a.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(a.normalsBuf),e.bindArray++),a.indicesBuf?(a.indicesBuf.bind(),e.bindArray++):a.positionsBuf,this._lastGeometryId=a.id),a.indicesBuf?(s.drawElements(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0),e.drawElements++):a.positionsBuf&&(s.drawArrays(s.TRIANGLES,0,a.positionsBuf.numItems),e.drawArrays++)},EmphasisFillRenderer.prototype._allocate=function(e){const t=e.scene._lightsState,i=e.scene._sectionPlanesState,s=e.scene.canvas.gl;if(this._program=new Program(s,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._uModelNormalMatrix=r.getLocation("modelNormalMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uViewNormalMatrix=r.getLocation("viewNormalMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var o=0,a=t.lights.length;o<a;o++){switch(t.lights[o].type){case"ambient":this._uLightAmbient[o]=r.getLocation("lightAmbient");break;case"dir":this._uLightColor[o]=r.getLocation("lightColor"+o),this._uLightPos[o]=null,this._uLightDir[o]=r.getLocation("lightDir"+o);break;case"point":this._uLightColor[o]=r.getLocation("lightColor"+o),this._uLightPos[o]=r.getLocation("lightPos"+o),this._uLightDir[o]=null,this._uLightAttenuation[o]=r.getLocation("lightAttenuation"+o)}}this._uSectionPlanes=[];for(o=0,a=i.sectionPlanes.length;o<a;o++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+o),pos:r.getLocation("sectionPlanePos"+o),dir:r.getLocation("sectionPlaneDir"+o)});this._uFillColor=r.getLocation("fillColor"),this._aPosition=r.getAttribute("position"),this._aNormal=r.getAttribute("normal"),this._uClippable=r.getLocation("clippable"),this._uGammaFactor=r.getLocation("gammaFactor"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},EmphasisFillRenderer.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t._sectionPlanesState,r=t._lightsState,o=t.camera,a=o._state;let n;this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,i.uniformMatrix4fv(this._uViewMatrix,!1,a.matrix),i.uniformMatrix4fv(this._uViewNormalMatrix,!1,a.normalMatrix),i.uniformMatrix4fv(this._uProjMatrix,!1,o.project._state.matrix);for(var l=0,h=r.lights.length;l<h;l++)n=r.lights[l],this._uLightAmbient[l]?i.uniform4f(this._uLightAmbient[l],n.color[0],n.color[1],n.color[2],n.intensity):(this._uLightColor[l]&&i.uniform4f(this._uLightColor[l],n.color[0],n.color[1],n.color[2],n.intensity),this._uLightPos[l]&&(i.uniform3fv(this._uLightPos[l],n.pos),this._uLightAttenuation[l]&&i.uniform1f(this._uLightAttenuation[l],n.attenuation)),this._uLightDir[l]&&i.uniform3fv(this._uLightDir[l],n.dir));if(s.sectionPlanes.length>0){const e=t._sectionPlanesState.sectionPlanes;let s,r,o,a,n;for(l=0,h=this._uSectionPlanes.length;l<h;l++)r=(s=this._uSectionPlanes[l]).active,o=e[l],r&&i.uniform1i(r,o.active),(a=s.pos)&&i.uniform3fv(s.pos,o.pos),(n=s.dir)&&i.uniform3fv(s.dir,o.dir)}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor)};class EmphasisEdgesShaderSource{constructor(e){this.vertex=buildVertex$1(e),this.fragment=buildFragment$1(e)}}function buildVertex$1(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Edges drawing vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vColor;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push("   mat[0][0] = 1.0;"),o.push("   mat[0][1] = 0.0;"),o.push("   mat[0][2] = 0.0;"),"spherical"===s&&(o.push("   mat[1][0] = 0.0;"),o.push("   mat[1][1] = 1.0;"),o.push("   mat[1][2] = 0.0;")),o.push("   mat[2][0] = 0.0;"),o.push("   mat[2][1] = 0.0;"),o.push("   mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===s||"cylindrical"===s?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),o.push("vColor = edgeColor;"),t&&o.push("vWorldPosition = worldPosition;"),o.push("   gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$1(e){const t=e.scene._sectionPlanesState,i=e.scene.gammaOutput,s=t.sectionPlanes.length>0;let r,o;const a=[];if(a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),s)for(a.push("varying vec4 vWorldPosition;"),a.push("uniform bool clippable;"),r=0,o=t.sectionPlanes.length;r<o;r++)a.push("uniform bool sectionPlaneActive"+r+";"),a.push("uniform vec3 sectionPlanePos"+r+";"),a.push("uniform vec3 sectionPlaneDir"+r+";");if(a.push("varying vec4 vColor;"),a.push("void main(void) {"),s){for(a.push("if (clippable) {"),a.push("  float dist = 0.0;"),r=0,o=t.sectionPlanes.length;r<o;r++)a.push("if (sectionPlaneActive"+r+") {"),a.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),a.push("}");a.push("  if (dist > 0.0) { discard; }"),a.push("}")}return a.push("gl_FragColor = vColor;"),i?a.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):a.push("gl_FragColor = vColor;"),a.push("}"),a}const ids$4=new Map({}),EmphasisEdgesRenderer=function(e,t){this.id=ids$4.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new EmphasisEdgesShaderSource(t),this._allocate(t)},renderers={};EmphasisEdgesRenderer.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=renderers[t];return i||(i=new EmphasisEdgesRenderer(t,e),renderers[t]=i,stats.memory.programs++),i._useCount++,i},EmphasisEdgesRenderer.prototype.put=function(){0==--this._useCount&&(ids$4.removeItem(this.id),this._program&&this._program.destroy(),delete renderers[this._hash],stats.memory.programs--)},EmphasisEdgesRenderer.prototype.webglContextRestored=function(){this._program=null},EmphasisEdgesRenderer.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene.canvas.gl;let r;const o=t._state,a=t._geometry,n=a._state;switch(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;case 3:default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){const t=r.backfaces;if(e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t),e.lineWidth!==r.edgeWidth&&(s.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){const e=r.edgeColor,t=r.edgeAlpha;s.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=r.id}let l;s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uModelNormalMatrix&&s.uniformMatrix4fv(this._uModelNormalMatrix,s.FALSE,t.worldNormalMatrix),this._uClippable&&s.uniform1i(this._uClippable,o.clippable),n.primitive===s.TRIANGLES?l=a._getEdgeIndices():n.primitive===s.LINES&&(l=n.indicesBuf),l&&(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++),l.bind(),e.bindArray++,this._lastGeometryId=n.id),s.drawElements(s.LINES,l.numItems,l.itemType,0),e.drawElements++)},EmphasisEdgesRenderer.prototype._allocate=function(e){const t=e.scene.canvas.gl,i=e.scene._sectionPlanesState;if(this._program=new Program(t,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,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=s.getLocation("edgeColor"),this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uGammaFactor=s.getLocation("gammaFactor"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},EmphasisEdgesRenderer.prototype._bindProgram=function(e){const t=this._program,i=this._scene,s=i.canvas.gl,r=i._sectionPlanesState,o=i.camera,a=o._state;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.uniformMatrix4fv(this._uViewMatrix,!1,a.matrix),s.uniformMatrix4fv(this._uProjMatrix,!1,o.project._state.matrix),r.sectionPlanes.length>0){const e=r.sectionPlanes;let t,i,o,a,n;for(let r=0,l=this._uSectionPlanes.length;r<l;r++)i=(t=this._uSectionPlanes[r]).active,o=e[r],i&&s.uniform1i(i,o.active),(a=t.pos)&&s.uniform3fv(t.pos,o.pos),(n=t.dir)&&s.uniform3fv(t.dir,o.dir)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)};class PickMeshShaderSource{constructor(e){this.vertex=buildVertex$2(e),this.fragment=buildFragment$2(e)}}function buildVertex$2(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Mesh picking vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("varying vec4 vViewPosition;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push("   mat[0][0] = 1.0;"),o.push("   mat[0][1] = 0.0;"),o.push("   mat[0][2] = 0.0;"),"spherical"===s&&(o.push("   mat[1][0] = 0.0;"),o.push("   mat[1][1] = 1.0;"),o.push("   mat[1][2] = 0.0;")),o.push("   mat[2][0] = 0.0;"),o.push("   mat[2][1] = 0.0;"),o.push("   mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==s&&"cylindrical"!==s||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);")),o.push("   vec4 worldPosition = modelMatrix2 * localPosition;"),o.push("   vec4 viewPosition = viewMatrix2 * worldPosition;"),t&&o.push("   vWorldPosition = worldPosition;"),o.push("   gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$2(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Mesh 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"),s.push("uniform vec4 pickColor;"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("void main(void) {"),i){s.push("if (clippable) {"),s.push("  float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = pickColor; "),s.push("}"),s}const PickMeshRenderer=function(e,t){this._hash=e,this._shaderSource=new PickMeshShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$1={};PickMeshRenderer.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=renderers$1[t];if(!i){if((i=new PickMeshRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$1[t]=i,stats.memory.programs++}return i._useCount++,i},PickMeshRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$1[this._hash],stats.memory.programs--)},PickMeshRenderer.prototype.webglContextRestored=function(){this._program=null},PickMeshRenderer.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),this._lastMaterialId=s.id}i.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix),i.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),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);var o=t._state.pickID;const a=o>>24&255,n=o>>16&255,l=o>>8&255,h=255&o;i.uniform4f(this._uPickColor,h/255,l/255,n/255,a/255),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)},PickMeshRenderer.prototype._allocate=function(e){const t=e.scene.canvas.gl;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e.scene._sectionPlanesState.sectionPlanes.length;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._uClippable=i.getLocation("clippable"),this._uPickColor=i.getLocation("pickColor"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},PickMeshRenderer.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.sectionPlanes.length>0){let e,t,r,o,a;for(let n=0,l=this._uSectionPlanes.length;n<l;n++)t=(e=this._uSectionPlanes[n]).active,r=s.sectionPlanes[n],t&&i.uniform1i(t,r.active),(o=e.pos)&&i.uniform3fv(e.pos,r.pos),(a=e.dir)&&i.uniform3fv(e.dir,r.dir)}};class PickTriangleShaderSource{constructor(e){this.vertex=buildVertex$3(e),this.fragment=buildFragment$3(e)}}function buildVertex$3(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=(e._state.billboard,e._state.stationary,[]);return s.push("// Surface picking vertex shader"),s.push("attribute vec3 position;"),s.push("attribute vec4 color;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),t&&(s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;")),s.push("varying vec4 vColor;"),i&&s.push("uniform mat4 positionsDecodeMatrix;"),s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;"),s.push("   vec4 worldPosition = modelMatrix * localPosition; "),s.push("   vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push("   vWorldPosition = worldPosition;"),s.push("   vColor = color;"),s.push("   gl_Position = projMatrix * viewPosition;"),s.push("}"),s}function buildFragment$3(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Surface 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"),s.push("varying vec4 vColor;"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("void main(void) {"),i){s.push("if (clippable) {"),s.push("  float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = vColor;"),s.push("}"),s}const PickTriangleRenderer=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new PickTriangleShaderSource(t),this._allocate(t)},renderers$2={};PickTriangleRenderer.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=renderers$2[t];if(!i){if((i=new PickTriangleRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$2[t]=i,stats.memory.programs++}return i._useCount++,i},PickTriangleRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$2[this._hash],stats.memory.programs--)},PickTriangleRenderer.prototype.webglContextRestored=function(){this._program=null},PickTriangleRenderer.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=i._sectionPlanesState,o=t._material._state,a=(t._state,t._geometry),n=t._geometry._state,l=o.backfaces,h=o.frontface,c=a._getPickTrianglePositions(),d=a._getPickTriangleColors();i.camera._state;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.sectionPlanes.length>0){const e=r.sectionPlanes;let t,i,o,a,n;for(let r=0,l=this._uSectionPlanes.length;r<l;r++)i=(t=this._uSectionPlanes[r]).active,o=e[r],i&&s.uniform1i(i,o.active),(a=t.pos)&&s.uniform3fv(t.pos,o.pos),(n=t.dir)&&s.uniform3fv(t.dir,o.dir)}e.backfaces!==l&&(l?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=l),e.frontface!==h&&(h?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=h),this._lastMaterialId=o.id,s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),this._uPositionsDecodeMatrix?(s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(c,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT)):this._aPosition.bindArrayBuffer(c),d.bind(),s.enableVertexAttribArray(this._aColor.location),s.vertexAttribPointer(this._aColor.location,d.itemSize,d.itemType,!0,0,0),s.drawArrays(n.primitive,0,c.numItems/3)},PickTriangleRenderer.prototype._allocate=function(e){const t=e.scene.canvas.gl;if(this._program=new Program(t,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e.scene._sectionPlanesState.sectionPlanes.length;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._aColor=i.getAttribute("color"),this._uClippable=i.getLocation("clippable")};class OcclusionShaderSource{constructor(e){this.vertex=buildVertex$4(e),this.fragment=buildFragment$4(e)}}function buildVertex$4(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=e._state.billboard,r=e._state.stationary,o=[];return o.push("// Mesh occlusion vertex shader"),o.push("attribute vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),i&&o.push("uniform mat4 positionsDecodeMatrix;"),t&&o.push("varying vec4 vWorldPosition;"),"spherical"!==s&&"cylindrical"!==s||(o.push("void billboard(inout mat4 mat) {"),o.push("   mat[0][0] = 1.0;"),o.push("   mat[0][1] = 0.0;"),o.push("   mat[0][2] = 0.0;"),"spherical"===s&&(o.push("   mat[1][0] = 0.0;"),o.push("   mat[1][1] = 1.0;"),o.push("   mat[1][2] = 0.0;")),o.push("   mat[2][0] = 0.0;"),o.push("   mat[2][1] = 0.0;"),o.push("   mat[2][2] =1.0;"),o.push("}")),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),i&&o.push("localPosition = positionsDecodeMatrix * localPosition;"),o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),r&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==s&&"cylindrical"!==s||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);")),o.push("   vec4 worldPosition = modelMatrix2 * localPosition;"),o.push("   vec4 viewPosition = viewMatrix2 * worldPosition;"),t&&o.push("   vWorldPosition = worldPosition;"),o.push("   gl_Position = projMatrix * viewPosition;"),o.push("}"),o}function buildFragment$4(e){const t=e.scene._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Mesh 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"),i){s.push("uniform bool clippable;"),s.push("varying vec4 vWorldPosition;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("void main(void) {"),i){s.push("if (clippable) {"),s.push("  float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}const OcclusionRenderer=function(e,t){this._hash=e,this._shaderSource=new OcclusionShaderSource(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},renderers$3={};OcclusionRenderer.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=renderers$3[t];if(!i){if((i=new OcclusionRenderer(t,e)).errors)return console.log(i.errors.join("\n")),null;renderers$3[t]=i,stats.memory.programs++}return i._useCount++,i},OcclusionRenderer.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete renderers$3[this._hash],stats.memory.programs--)},OcclusionRenderer.prototype.webglContextRestored=function(){this._program=null},OcclusionRenderer.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._geometry._state;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 a=i.camera,n=a._state;s.uniformMatrix4fv(this._uViewMatrix,!1,n.matrix),s.uniformMatrix4fv(this._uProjMatrix,!1,a._project._state.matrix),s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf,o.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),o.indicesBuf&&(o.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=o.id),o.indicesBuf?(s.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positions&&s.drawArrays(s.TRIANGLES,0,o.positions.numItems)},OcclusionRenderer.prototype._allocate=function(e){const t=e.scene.canvas.gl;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e.scene._sectionPlanesState.sectionPlanes.length;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._uClippable=i.getLocation("clippable"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},OcclusionRenderer.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.sectionPlanes.length>0){let e,t,r,o,a;for(let n=0,l=this._uSectionPlanes.length;n<l;n++)t=(e=this._uSectionPlanes[n]).active,r=s.sectionPlanes[n],t&&i.uniform1i(t,r.active),(o=e.pos)&&i.uniform3fv(e.pos,r.pos),(a=e.dir)&&i.uniform3fv(e.dir,r.dir)}};const obb=math.OBB3(),angleAxis$1=new Float32Array(4),q1$1=new Float32Array(4),q2$1=new Float32Array(4),xAxis$1=new Float32Array([1,0,0]),yAxis$1=new Float32Array([0,1,0]),zAxis$1=new Float32Array([0,0,1]),veca$1=new Float32Array(3),vecb$1=new Float32Array(3),identityMat$1=math.identityMat4();class Mesh extends Component{get type(){return"Mesh"}constructor(e,t={}){if(super(e,t),this._state=new RenderState({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:""}),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=math.vec3(),this._quaternion=math.identityQuaternion(),this._rotation=math.vec3(),this._position=math.vec3(),this._worldMatrix=math.identityMat4(),this._worldNormalMatrix=math.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0,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,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 isMesh(){return!0}get parent(){return this._parentNode}_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=DrawRenderer.get(this),this._emphasisFillRenderer=EmphasisFillRenderer.get(this),this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this));const t=this._makePickHash();this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=PickMeshRenderer.get(this));const i=this._makeOcclusionHash();this._state.occlusionHash!==i&&(this._state.occlusionHash=i,this._putOcclusionRenderer(),this._occlusionRenderer=OcclusionRenderer.get(this))}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)math.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=math.mat4()),math.transposeMat4(this._worldMatrix,this._worldNormalMatrix),math.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=math.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){math.transformOBB3(e,this._geometry.obb,obb),math.OBB3ToAABB3(obb,t)}get geometry(){return this._geometry}get material(){return this._material}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]),math.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]),math.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=math.identityMat4()),this.__localMatrix.set(e||identityMat$1),math.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=math.identityMat4()),math.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}rotate(e,t){return angleAxis$1[0]=e[0],angleAxis$1[1]=e[1],angleAxis$1[2]=e[2],angleAxis$1[3]=t*math.DEGTORAD,math.angleAxisToQuaternion(angleAxis$1,q1$1),math.mulQuaternions(this.quaternion,q1$1,q2$1),this.quaternion=q2$1,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return angleAxis$1[0]=e[0],angleAxis$1[1]=e[1],angleAxis$1[2]=e[2],angleAxis$1[3]=t*math.DEGTORAD,math.angleAxisToQuaternion(angleAxis$1,q1$1),math.mulQuaternions(q1$1,this.quaternion,q1$1),this}rotateX(e){return this.rotate(xAxis$1,e)}rotateY(e){return this.rotate(yAxis$1,e)}rotateZ(e){return this.rotate(zAxis$1,e)}translate(e,t){return math.vec3ApplyQuaternion(this.quaternion,e,veca$1),math.mulVec3Scalar(veca$1,t,vecb$1),math.addVec3(this.position,vecb$1,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(xAxis$1,e)}translateY(e){return this.translate(yAxis$1,e)}translateZ(e){return this.translate(zAxis$1,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)}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this),this.glRedraw()}get visible(){return this._state.visible}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this),this.glRedraw())}get xrayed(){return this._state.xrayed}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this),this.glRedraw())}get highlighted(){return this._state.highlighted}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this),this.glRedraw())}get selected(){return this._state.selected}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set culled(e){this._state.culled=!!e,this.glRedraw()}get culled(){return this._state.culled}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get clippable(){return this._state.clippable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get collidable(){return this._state.collidable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get pickable(){return this._state.pickable}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get castsShadow(){return this._state.castsShadow}set receivesShadow(e){this._state.receivesShadow=!1}get receivesShadow(){return this._state.receivesShadow}get saoEnabled(){return!1}set colorize(e){let t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[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 colorize(){return this._state.colorize}set opacity(e){let t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[0]=1,t[1]=1,t[2]=1),t[3]=null!==e&&void 0!==e?e:1,this.glRedraw()}get opacity(){return this._state.colorize[3]}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get layer(){return this._state.layer}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get isDrawable(){return!0}get isStateSortable(){return!0}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}getRenderFlags(e){e.reset();const t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedFillTransparent=!0:e.xrayedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.normalFillTransparent=!0:e.normalFillOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.normalEdgesTransparent=!0:e.normalEdgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedFillTransparent=!0:e.selectedFillOpaque=!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.highlightedFillTransparent=!0:e.highlightedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}drawNormalFillOpaque(e){(this._drawRenderer||(this._drawRenderer=DrawRenderer.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawNormalEdgesOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawNormalFillTransparent(e){(this._drawRenderer||(this._drawRenderer=DrawRenderer.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawNormalEdgesTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawXRayedFillOpaque(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=EmphasisFillRenderer.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawXRayedEdgesOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawXRayedFillTransparent(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=EmphasisFillRenderer.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawXRayedEdgesTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawHighlightedFillOpaque(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=EmphasisFillRenderer.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawHighlightedEdgesOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawHighlightedFillTransparent(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=EmphasisFillRenderer.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawHighlightedEdgesTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawSelectedFillOpaque(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=EmphasisFillRenderer.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawSelectedEdgesOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawSelectedFillTransparent(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=EmphasisFillRenderer.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawSelectedEdgesTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=PickMeshRenderer.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}drawOcclusion(e){(this._occlusionRenderer||(this._occlusionRenderer=OcclusionRenderer.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=PickTriangleRenderer.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,i){pickTriangleSurface(this,e,t,i)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){if(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),this._xrayed&&this.scene._objectXRayedUpdated(this,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1);const e=!1;this.scene._objectColorizeUpdated(this,e)}this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const pickTriangleSurface=function(){const e=math.vec3(),t=math.vec3(),i=math.vec3(),s=math.vec3(),r=math.vec3(),o=math.vec3(),a=math.vec4(),n=math.vec3(),l=math.vec3(),h=math.vec3(),c=math.vec3(),d=math.vec3(),u=math.vec3(),p=math.vec3(),m=math.vec3(),_=math.vec3(),g=math.vec4(),f=math.vec4(),v=math.vec4(),b=math.vec3(),y=math.vec3(),M=math.vec3(),w=math.vec3(),x=math.vec3(),P=math.vec3(),E=math.vec3(),A=math.vec3(),C=math.vec3(),S=math.vec3(),R=math.vec3();return function(L,D,k,T){var I=T.primIndex;if(void 0!==I&&null!==I&&I>-1){const V=L.geometry._state,O=L.scene,j=O.camera,U=O.canvas;if("triangles"===V.primitiveName){T.primitive="triangle";const O=I,G=V.indices,z=V.positions;let H,$,W,X;if(G){var B=G[O+0],F=G[O+1],N=G[O+2];o[0]=B,o[1]=F,o[2]=N,T.indices=o,H=3*B,$=3*F,W=3*N}else W=($=(H=3*O)+3)+3;if(i[0]=z[H+0],i[1]=z[H+1],i[2]=z[H+2],s[0]=z[$+0],s[1]=z[$+1],s[2]=z[$+2],r[0]=z[W+0],r[1]=z[W+1],r[2]=z[W+2],V.compressGeometry){const e=V.positionsDecodeMatrix;e&&(geometryCompressionUtils.decompressPosition(i,e,i),geometryCompressionUtils.decompressPosition(s,e,s),geometryCompressionUtils.decompressPosition(r,e,r))}T.canvasPos?(X=T.canvasPos,math.canvasPosToLocalRay(U.canvas,D,k,L.worldMatrix,X,e,t)):T.origin&&T.direction&&math.worldRayToLocalRay(L.worldMatrix,T.origin,T.direction,e,t),math.normalizeVec3(t),math.rayPlaneIntersect(e,t,i,s,r,a),T.localPos=a,T.position=a,g[0]=a[0],g[1]=a[1],g[2]=a[2],g[3]=1,math.transformVec4(L.worldMatrix,g,f),n[0]=f[0],n[1]=f[1],n[2]=f[2],T.worldPos=n,math.transformVec4(j.matrix,f,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],T.viewPos=l,math.cartesianToBarycentric(a,i,s,r,h),T.bary=h;const Y=V.normals;if(Y){if(V.compressGeometry){const e=3*B,t=3*F,i=3*N;geometryCompressionUtils.decompressNormal(Y.subarray(e,e+2),c),geometryCompressionUtils.decompressNormal(Y.subarray(t,t+2),d),geometryCompressionUtils.decompressNormal(Y.subarray(i,i+2),u)}else c[0]=Y[H],c[1]=Y[H+1],c[2]=Y[H+2],d[0]=Y[$],d[1]=Y[$+1],d[2]=Y[$+2],u[0]=Y[W],u[1]=Y[W+1],u[2]=Y[W+2];const e=math.addVec3(math.addVec3(math.mulVec3Scalar(c,h[0],b),math.mulVec3Scalar(d,h[1],y),M),math.mulVec3Scalar(u,h[2],w),x);T.worldNormal=math.normalizeVec3(math.transformVec3(L.worldNormalMatrix,e,P))}const q=V.uv;if(q){if(p[0]=q[2*B],p[1]=q[2*B+1],m[0]=q[2*F],m[1]=q[2*F+1],_[0]=q[2*N],_[1]=q[2*N+1],V.compressGeometry){const e=V.uvDecodeMatrix;e&&(geometryCompressionUtils.decompressUV(p,e,p),geometryCompressionUtils.decompressUV(m,e,m),geometryCompressionUtils.decompressUV(_,e,_))}T.uv=math.addVec3(math.addVec3(math.mulVec2Scalar(p,h[0],E),math.mulVec2Scalar(m,h[1],A),C),math.mulVec2Scalar(_,h[2],S),R)}}}}}();function buildSphereGeometry(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 a=e.heightSegments||18;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);let n=e.widthSegments||18;n<0&&(console.error("negative widthSegments not allowed - will invert"),n*=-1),(n=Math.floor(t*n))<18&&(n=18);const l=[],h=[],c=[],d=[];let u,p,m,_,g,f,v,b,y,M,w,x,P,E,A;for(u=0;u<=a;u++)for(m=u*Math.PI/a,_=Math.sin(m),g=Math.cos(m),p=0;p<=n;p++)f=2*p*Math.PI/n,v=Math.sin(f),y=(b=Math.cos(f))*_,M=g,w=v*_,x=1-p/n,P=u/a,h.push(y),h.push(M),h.push(w),c.push(x),c.push(P),l.push(i+o*y),l.push(s+o*M),l.push(r+o*w);for(u=0;u<a;u++)for(p=0;p<n;p++)A=(E=u*(n+1)+p)+n+1,d.push(E+1),d.push(A+1),d.push(A),d.push(E+1),d.push(A),d.push(E);return utils.apply(e,{positions:l,normals:h,uv:c,indices:d})}const zeroVec=new Float32Array([0,0,1]),quat=new Float32Array(4);class Control{constructor(e){this.id=null,this._viewer=e.viewer,this._visible=!1,this._pos=math.vec3(),this._baseDir=math.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane=e,e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),this._rootNode.position=e}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=math.vec3PairToQuaternion(zeroVec,e,quat)}setVisible(e=!0){if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}getVisible(){return this._visible}setCulled(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}_createNodes(){const e=this._viewer.scene;this._rootNode=new Node(e,{position:[0,0,0],scale:[5,5,5]});const t=this._rootNode,i={arrowHead:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.01,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new ReadableGeometry(t,buildTorusGeometry({radius:.8,tube:.01,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.01,radiusBottom:.01,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new ReadableGeometry(t,buildCylinderGeometry({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},s={pickable:new PhongMaterial(t,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new PhongMaterial(t,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new PhongMaterial(t,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new PhongMaterial(t,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new PhongMaterial(t,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new EmphasisMaterial(t,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new EmphasisMaterial(t,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new PhongMaterial(t,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new EmphasisMaterial(t,{edges:!1,filled:!0,fillColor:[1,1,0],edgeColor:[0,0,0],fillAlpha:.1,backfaces:!0}),pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),!1),planeFrame:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildTorusGeometry({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new PhongMaterial(t,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new EmphasisMaterial(t,{edges:!1,edgeColor:[0,0,0],filled:!0,fillColor:[.8,.8,.8],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),!1),xCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.red,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,-.07,-.8,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(0*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),xCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,-.8,-.07,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),yCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),yCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(.07,0,-.8,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(.8,0,-.07,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurve:t.addChild(new Mesh(t,{geometry:i.curve,material:s.blue,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zCurveHandle:t.addChild(new Mesh(t,{geometry:i.curveHandle,material:s.pickable,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurveCurveArrow1:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(.8,-.07,0,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4());return math.mulMat4(e,t,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zCurveArrow2:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(.05,-.8,0,math.identityMat4()),t=math.scaleMat4v([.6,.6,.6],math.identityMat4()),i=math.rotationMat4v(90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(math.mulMat4(e,t,math.identityMat4()),i,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),center:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildSphereGeometry({radius:.05})),material:s.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.red,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),xAxis:t.addChild(new Mesh(t,{geometry:i.axis,material:s.red,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),xAxisHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.green,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2}),!1),yShaft:t.addChild(new Mesh(t,{geometry:i.axis,material:s.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yShaftHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHead,material:s.blue,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrowHandle:t.addChild(new Mesh(t,{geometry:i.arrowHeadHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),!1),zShaft:t.addChild(new Mesh(t,{geometry:i.axis,material:s.blue,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),!1),zAxisHandle:t.addChild(new Mesh(t,{geometry:i.axisHandle,material:s.pickable,matrix:function(){const e=math.translateMat4c(0,.5,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1}),!1)},this._affordanceMeshes={planeFrame:t.addChild(new Mesh(t,{geometry:new ReadableGeometry(t,buildTorusGeometry({center:[0,0,0],radius:2,tube:.01,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new PhongMaterial(t,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new EmphasisMaterial(t,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45]}),!1),xHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.red,highlighted:!0,highlightMaterial:s.highlightRed,matrix:function(){const e=math.rotationMat4v(90*math.DEGTORAD,[0,1,0],math.identityMat4()),t=math.rotationMat4v(270*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.green,highlighted:!0,highlightMaterial:s.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zHoop:t.addChild(new Mesh(t,{geometry:i.hoop,material:s.blue,highlighted:!0,highlightMaterial:s.highlightBlue,matrix:math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),!1),xAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.red,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[0,0,1],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),yAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.green,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(180*math.DEGTORAD,[1,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1),zAxisArrow:t.addChild(new Mesh(t,{geometry:i.arrowHeadBig,material:s.blue,matrix:function(){const e=math.translateMat4c(0,1.1,0,math.identityMat4()),t=math.rotationMat4v(-90*math.DEGTORAD,[.8,0,0],math.identityMat4());return math.mulMat4(t,e,math.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),!1)}}_bindEvents(){const e=this;var t=!1;const i=-1,s=0,r=1,o=2,a=3,n=4,l=5,h=this._rootNode;var c=null,d=null;const u=math.vec2(),p=math.vec3([1,0,0]),m=math.vec3([0,1,0]),_=math.vec3([0,0,1]),g=this._viewer.scene.canvas.canvas,f=this._viewer.camera,v=this._viewer.scene;{const e=math.vec3([0,0,0]);var b=-1;this._onCameraViewMatrix=v.camera.on("viewMatrix",()=>{}),this._onCameraProjMatrix=v.camera.on("projMatrix",()=>{}),this._onSceneTick=v.on("tick",()=>{var t=Math.abs(math.lenVec3(math.subVec3(v.camera.eye,h.position,e)));if(t!==b){var i=t/50*10;h.scale=[i,i,i],b=t}})}const y=function(){const e=new Float32Array(2);return function(t){if(t){for(var i=t.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-s,e[1]=t.pageY-r}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),M=function(){const t=math.mat4();return function(i,s){return math.quaternionToMat4(e._rootNode.quaternion,t),math.transformVec3(t,i,s),math.normalizeVec3(s),s}}();var w=function(){const e=math.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?math.cross3Vec3(t,[0,1,0],e):math.cross3Vec3(t,[1,0,0],e),math.cross3Vec3(e,t,e),math.normalizeVec3(e),e}}();const x=function(){const t=math.vec3(),i=math.vec3(),s=math.vec4();return function(r,o,a){M(r,s);const n=w(s,o,a);E(o,n,t),E(a,n,i),math.subVec3(i,t);const l=math.dotVec3(i,s);e._pos[0]+=s[0]*l,e._pos[1]+=s[1]*l,e._pos[2]+=s[2]*l,e._rootNode.position=e._pos,e.sectionPlane&&(e.sectionPlane.pos=e._pos)}}();var P=function(){const t=math.vec4(),i=math.vec4(),s=math.vec4(),r=math.vec4();return function(o,a,n){if(M(o,r),!(E(a,r,t)&&E(n,r,i))){const e=w(r,a,n);E(a,e,t,1),E(n,e,i,1);var l=math.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=math.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}math.normalizeVec3(t),math.normalizeVec3(i),l=math.dotVec3(t,i),l=math.clamp(l,-1,1);var h=Math.acos(l)*math.RADTODEG;math.cross3Vec3(t,i,s),math.dotVec3(s,r)<0&&(h=-h),e._rootNode.rotate(o,h),A()}}(),E=function(){const t=math.vec4([0,0,0,1]),i=math.mat4();return function(s,r,o,a){a=a||0,t[0]=s[0]/g.width*2-1,t[1]=-(s[1]/g.height*2-1),t[2]=0,t[3]=1,math.mulMat4(f.projMatrix,f.viewMatrix,i),math.inverseMat4(i),math.transformVec4(i,t,t),math.mulVec4Scalar(t,1/t[3]);var n=f.eye;math.subVec4(t,n,t);const l=e._sectionPlane.pos;var h=-math.dotVec3(l,r)-a,c=math.dotVec3(r,t);if(Math.abs(c)>.005){var d=-(math.dotVec3(r,n)+h)/c;return math.mulVec3Scalar(t,d,o),math.addVec3(o,n),math.subVec3(o,l,o),!0}return!1}}();const A=function(){const t=math.vec3(),i=math.mat4();return function(){e.sectionPlane&&(math.quaternionToMat4(h.quaternion,i),math.transformVec3(i,[0,0,1],t),e._sectionPlane.dir=t)}}();var C,S=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",e=>{if(!this._visible)return;if(S)return;var h;switch(t=!1,C&&(C.visible=!1),e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:h=this._affordanceMeshes.xAxisArrow,c=s;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:h=this._affordanceMeshes.yAxisArrow,c=r;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:h=this._affordanceMeshes.zAxisArrow,c=o;break;case this._displayMeshes.xCurveHandle.id:h=this._affordanceMeshes.xHoop,c=a;break;case this._displayMeshes.yCurveHandle.id:h=this._affordanceMeshes.yHoop,c=n;break;case this._displayMeshes.zCurveHandle.id:h=this._affordanceMeshes.zHoop,c=l;break;default:return void(c=i)}h&&(h.visible=!0),C=h,t=!0}),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOut",e=>{this._visible&&(C&&(C.visible=!1),C=null,c=i)}),g.addEventListener("mousedown",this._canvasMouseDownListener=(e=>{if(e.preventDefault(),this._visible&&t)switch(this._viewer.cameraControl.pointerEnabled=!1,e.which){case 1:S=!0;var i=y(e);d=c,u[0]=i[0],u[1]=i[1]}})),g.addEventListener("mousemove",this._canvasMouseMoveListener=(e=>{if(!this._visible)return;if(!S)return;var t=y(e);const i=t[0],h=t[1];switch(d){case s:x(p,u,t);break;case r:x(m,u,t);break;case o:x(_,u,t);break;case a:P(p,u,t);break;case n:P(m,u,t);break;case l:P(_,u,t)}u[0]=i,u[1]=h})),g.addEventListener("mouseup",this._canvasMouseUpListener=(e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,S&&(e.which,S=!1,t=!1))})),g.addEventListener("wheel",this._canvasWheelListener=(e=>{if(this._visible)Math.max(-1,Math.min(1,40*-e.deltaY))}))}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=e.cameraControl;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix),r.off(this._onCameraControlHover),r.off(this._onCameraControlHoverLeave)}_destroyNodes(){this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}const defaultCSS=".sk-fading-circle {        background: transparent;        margin: 20px auto;        width: 50px;        height:50px;        position: relative;        }        .sk-fading-circle .sk-circle {        width: 120%;        height: 120%;        position: absolute;        left: 0;        top: 0;        }        .sk-fading-circle .sk-circle:before {        content: '';        display: block;        margin: 0 auto;        width: 15%;        height: 15%;        background-color: #ff8800;        border-radius: 100%;        -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both;        animation: sk-circleFadeDelay 1.2s infinite ease-in-out both;        }        .sk-fading-circle .sk-circle2 {        -webkit-transform: rotate(30deg);        -ms-transform: rotate(30deg);        transform: rotate(30deg);    }    .sk-fading-circle .sk-circle3 {        -webkit-transform: rotate(60deg);        -ms-transform: rotate(60deg);        transform: rotate(60deg);    }    .sk-fading-circle .sk-circle4 {        -webkit-transform: rotate(90deg);        -ms-transform: rotate(90deg);        transform: rotate(90deg);    }    .sk-fading-circle .sk-circle5 {        -webkit-transform: rotate(120deg);        -ms-transform: rotate(120deg);        transform: rotate(120deg);    }    .sk-fading-circle .sk-circle6 {        -webkit-transform: rotate(150deg);        -ms-transform: rotate(150deg);        transform: rotate(150deg);    }    .sk-fading-circle .sk-circle7 {        -webkit-transform: rotate(180deg);        -ms-transform: rotate(180deg);        transform: rotate(180deg);    }    .sk-fading-circle .sk-circle8 {        -webkit-transform: rotate(210deg);        -ms-transform: rotate(210deg);        transform: rotate(210deg);    }    .sk-fading-circle .sk-circle9 {        -webkit-transform: rotate(240deg);        -ms-transform: rotate(240deg);        transform: rotate(240deg);    }    .sk-fading-circle .sk-circle10 {        -webkit-transform: rotate(270deg);        -ms-transform: rotate(270deg);        transform: rotate(270deg);    }    .sk-fading-circle .sk-circle11 {        -webkit-transform: rotate(300deg);        -ms-transform: rotate(300deg);        transform: rotate(300deg);    }    .sk-fading-circle .sk-circle12 {        -webkit-transform: rotate(330deg);        -ms-transform: rotate(330deg);        transform: rotate(330deg);    }    .sk-fading-circle .sk-circle2:before {        -webkit-animation-delay: -1.1s;        animation-delay: -1.1s;    }    .sk-fading-circle .sk-circle3:before {        -webkit-animation-delay: -1s;        animation-delay: -1s;    }    .sk-fading-circle .sk-circle4:before {        -webkit-animation-delay: -0.9s;        animation-delay: -0.9s;    }    .sk-fading-circle .sk-circle5:before {        -webkit-animation-delay: -0.8s;        animation-delay: -0.8s;    }    .sk-fading-circle .sk-circle6:before {        -webkit-animation-delay: -0.7s;        animation-delay: -0.7s;    }    .sk-fading-circle .sk-circle7:before {        -webkit-animation-delay: -0.6s;        animation-delay: -0.6s;    }    .sk-fading-circle .sk-circle8:before {        -webkit-animation-delay: -0.5s;        animation-delay: -0.5s;    }    .sk-fading-circle .sk-circle9:before {        -webkit-animation-delay: -0.4s;        animation-delay: -0.4s;    }    .sk-fading-circle .sk-circle10:before {        -webkit-animation-delay: -0.3s;        animation-delay: -0.3s;    }    .sk-fading-circle .sk-circle11:before {        -webkit-animation-delay: -0.2s;        animation-delay: -0.2s;    }    .sk-fading-circle .sk-circle12:before {        -webkit-animation-delay: -0.1s;        animation-delay: -0.1s;    }    @-webkit-keyframes sk-circleFadeDelay {        0%, 39%, 100% { opacity: 0; }        40% { opacity: 1; }    }    @keyframes sk-circleFadeDelay {        0%, 39%, 100% { opacity: 0; }        40% { opacity: 1; }    }";class Spinner extends Component{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle">                <div class="sk-circle1 sk-circle"></div>                <div class="sk-circle2 sk-circle"></div>                <div class="sk-circle3 sk-circle"></div>                <div class="sk-circle4 sk-circle"></div>                <div class="sk-circle5 sk-circle"></div>                <div class="sk-circle6 sk-circle"></div>                <div class="sk-circle7 sk-circle"></div>                <div class="sk-circle8 sk-circle"></div>                <div class="sk-circle9 sk-circle"></div>                <div class="sk-circle10 sk-circle"></div>                <div class="sk-circle11 sk-circle"></div>                <div class="sk-circle12 sk-circle"></div>                </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){if(document.getElementById("xeokit-spinner-css"))return;const e=document.createElement("style");e.innerHTML=defaultCSS,e.id="xeokit-spinner-css",document.body.appendChild(e)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null)}}const WEBGL_CONTEXT_NAMES=["webgl","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Canvas extends Component{get type(){return"Canvas"}constructor(e,t={}){super(e,t),this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.canvas.width=this.canvas.clientWidth,this.canvas.height=this.canvas.clientHeight,this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=null,r=null,o=null,a=null,n=null,l=null,h=null;this._tick=this.scene.on("tick",function(){const e=i.canvas,t=window.innerWidth!==s||window.innerHeight!==r,c=e.clientWidth!==o||e.clientHeight!==a,d=e.offsetLeft!==n||e.offsetTop!==l,u=e.parentElement;if(t||c||d||u!==h){if(i._spinner._adjustPosition(),c||d){const t=e.clientWidth,s=e.clientHeight;if(c){let t,i=0;for(const e in core.scenes)core.scenes.hasOwnProperty(e)&&(i+=(t=core.scenes[e]).canvas.canvas.clientWidth*t.canvas.canvas.clientHeight);stats.memory.pixels=i,e.width=e.clientWidth,e.height=e.clientHeight}const r=i.boundary;r[0]=e.offsetLeft,r[1]=e.offsetTop,r[2]=t,r[3]=s,i.fire("boundary",r),o=t,a=s}t&&(s=window.innerWidth,r=window.innerHeight),d&&(n=e.offsetLeft,l=e.offsetTop),h=u}}),this._spinner=new Spinner(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId}),this.clearColorAmbient=t.clearColorAmbient}_createCanvas(){const e="xeokit-canvas-"+math.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<WEBGL_CONTEXT_NAMES.length;e++)try{this.gl=this.canvas.getContext(WEBGL_CONTEXT_NAMES[e],this.contextAttr)}catch(e){}if(this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0)),this.gl)if(this.webgl2)this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST);else if(WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_standard_derivatives){const e=this.gl.getExtension("OES_standard_derivatives");this.gl.hint(e.FRAGMENT_SHADER_DERIVATIVE_HINT_OES,this.gl.FASTEST)}}set clearColorAmbient(e){this._clearColorAmbient=!!e}get clearColorAmbient(){return this._clearColorAmbient}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}_getSnapshot(e={}){return this.scene._renderer.readImage(e)}readPixels(e,t,i,s){return this.scene._renderer.readPixels(e,t,i,s)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}get spinner(){return this._spinner}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class FrameContext{constructor(){this.reset()}reset(){this.lastProgramId=null,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickInvisible=!1,this.lineWidth=1}}class RenderFlags{constructor(){this.reset()}reset(){this.normalFillOpaque=!1,this.normalEdgesOpaque=!1,this.normalFillTransparent=!1,this.normalEdgesTransparent=!1,this.xrayedFillOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedFillTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedFillOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedFillTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedFillOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedFillTransparent=!1,this.selectedEdgesTransparent=!1}}const Canvas2Image=function(){const e=document.createElement("canvas"),t=String.fromCharCode;if(!e.getContext)return{saveAsBMP:function(){},saveAsPNG:function(){},saveAsJPEG:function(){}};const i=!!e.getContext("2d").getImageData,s=!!e.toDataURL,r=!!window.btoa,o=function(e){let i="";const s=e.width,r=e.height;i+="BM";let o=s*r*4+54;i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),i+=t(0,0,0,0,54,0,0,0),i+=t(40,0,0,0);let a=s;i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256);let n=r;i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),i+=t(1,0,32,0),i+=t(0,0,0,0);let l=s*r*4;i+=t(l%256),l=Math.floor(l/256),i+=t(l%256),l=Math.floor(l/256),i+=t(l%256),l=Math.floor(l/256),i+=t(l%256),i+=t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const h=e.data;let c,d,u,p,m="",_=r;do{for(u=s*(_-1)*4,p="",c=0;c<s;c++)p+=t(h[u+(d=4*c)+2],h[u+d+1],h[u+d],h[u+d+3]);m+=p}while(--_);return function(e){let i,s,r="";if("string"==typeof e)r=e;else for(s=e,i=0;i<s.length;i++)r+=t(s[i]);return btoa(r)}(i+m)},a=function(e){window.open(e)||(document.location.href=e)},n=function(e,t){return"data:"+t+";base64,"+e},l=function(e){const t=document.createElement("img");return t.src=e,t},h=function(e,t,i,s){if(t&&i){const r=document.createElement("canvas");r.width=t,r.height=i,r.style.width=t+"px",r.style.height=i+"px";const o=r.getContext("2d");return s?(o.save(),o.scale(1,-1),o.imageSmoothingEnabled=!0,o.drawImage(e,0,0,e.width,e.height,0,0,t,-i),o.restore()):(o.imageSmoothingEnabled=!0,o.drawImage(e,0,0,e.width,e.height,0,0,t,i)),r}return e};return{saveAsPNG:function(e,t,i,r,o){if(!s)return!1;const n=h(e,i,r,o).toDataURL("image/png");return t?l(n):(a(n),!0)},saveAsJPEG:function(e,t,i,r,o){if(!s)return!1;const n=h(e,i,r,o).toDataURL("image/jpeg");return 5==n.indexOf("image/jpeg")&&(t?l(n):(a(n),!0))},saveAsBMP:function(e,t,c,d,u){if(!(s&&i&&r))return!1;const p=function(e){const t=parseInt(e.width),i=parseInt(e.height);return e.getContext("2d").getImageData(0,0,t,i)}(h(e,c,d,u)),m=o(p);return t?l(n(m,"image/bmp")):(a(n(m,"image/bmp")),!0)}}}();class RenderBuffer{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(){if(this._touch(),this.bound)return;const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(){let e,t;const i=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=i.drawingBufferWidth,t=i.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const s=i.createTexture();i.bindTexture(i.TEXTURE_2D,s),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE);const r=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,r),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT16,e,t);const o=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,o),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,s,0),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,r),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,o),!i.isFramebuffer(o))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const a=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(a){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+a}this.buffer={framebuf:o,renderbuf:r,texture:s,width:e,height:t},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t){const i=e,s=this.gl.drawingBufferHeight-t,r=new Uint8Array(4),o=this.gl;return o.readPixels(i,s,1,1,o.RGBA,o.UNSIGNED_BYTE,r),r}readImage(e){const t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,o=i.imageData,a=i.context;t.readPixels(0,0,this.buffer.width,this.buffer.height,t.RGBA,t.UNSIGNED_BYTE,s),o.data.set(s),a.putImageData(o,0,0);const n=e.width||r.width,l=e.height||r.height,h=e.format||"jpeg";let c;switch(h){case"jpeg":c=Canvas2Image.saveAsJPEG(r,!0,n,l,!0);break;case"png":c=Canvas2Image.saveAsPNG(r,!0,n,l,!0);break;case"bmp":c=Canvas2Image.saveAsBMP(r,!0,n,l,!0);break;default:console.error("Unsupported image format: '"+h+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'jpeg'"),c=Canvas2Image.saveAsJPEG(r,!0,n,l,!0)}return c.src}_getImageDataCache(){const e=this.buffer.width,t=this.buffer.height;let i=this._imageDataCache;if(i&&(i.width===e&&i.height===t||(this._imageDataCache=null,i=null)),!i){const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d"),o=r.createImageData(e,t);i={pixelData:new Uint8Array(e*t*4),canvas:s,context:r,imageData:o,width:e,height:t},this._imageDataCache=i}return i}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(){const e=this;return{renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.texture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.texture),!0)},unbind:function(t){e.buffer&&e.buffer.texture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}}}destroy(){if(this.allocated){const e=this.gl;e.deleteTexture(this.buffer.texture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null}}class PickResult{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float32Array([0,0,0]),this._direction=new Float32Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float32Array([0,0,0]),this._worldPos=new Float32Array([0,0,0]),this._viewPos=new Float32Array([0,0,0]),this._bary=new Float32Array([0,0,0]),this._worldNormal=new Float32Array([0,0,0]),this._uv=new Float32Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this.entity&&this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1}}const MARKER_COLOR=math.vec3([1,0,0]),POINT_SIZE=20;class OcclusionTester{constructor(e){this._scene=e,this._markers={},this._markerList=[],this._markerIndices={},this._numMarkers=0,this._positions=[],this._indices=[],this._positionsBuf=null,this._indicesBuf=null,this._occlusionTestList=[],this._lenOcclusionTestList=0,this._pixels=[],this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markerListDirty=!1,this._positionsDirty=!1,this._vbosDirty=!1,this._occlusionTestListDirty=!1,this._lenPositionsBuf=0,e.camera.on("viewMatrix",()=>{this._occlusionTestListDirty=!0}),e.camera.on("projMatrix",()=>{this._occlusionTestListDirty=!0}),e.canvas.on("boundary",()=>{this._occlusionTestListDirty=!0})}addMarker(e){this._markers[e.id]=e,this._markerListDirty=!0}markerWorldPosUpdated(e){if(!this._markers[e.id])return;const t=this._markerIndices[e.id];this._positions[3*t+0]=e.worldPos[0],this._positions[3*t+1]=e.worldPos[1],this._positions[3*t+2]=e.worldPos[2],this._positionsDirty=!0}removeMarker(e){delete this._markers[e.id],this._markerListDirty=!0}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._markerListDirty&&(this._buildMarkerList(),this._markerListDirty=!1,this._positionsDirty=!0,this._occlusionTestListDirty=!0),this._positionsDirty&&(this._buildPositions(),this._positionsDirty=!1,this._vbosDirty=!0),this._vbosDirty&&(this._buildVBOs(),this._vbosDirty=!1),this._occlusionTestListDirty&&this._buildOcclusionTestList(),this._readPixelBuf=this._readPixelBuf||(this._readPixelBuf=new RenderBuffer(this._scene.canvas.canvas,this._scene.canvas.gl)),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene._sectionPlanesState.sectionPlanes.length>0,t=[];return t.push("// Mesh occlusion vertex shader"),t.push("attribute vec3 position;"),t.push("uniform mat4 modelMatrix;"),t.push("uniform mat4 viewMatrix;"),t.push("uniform mat4 projMatrix;"),e&&t.push("varying vec4 vWorldPosition;"),t.push("void main(void) {"),t.push("vec4 worldPosition = vec4(position, 1.0); "),t.push("   vec4 viewPosition = viewMatrix * worldPosition;"),e&&t.push("   vWorldPosition = worldPosition;"),t.push("   gl_Position = projMatrix * viewPosition;"),t.push("   gl_PointSize = "+POINT_SIZE+".0;"),t.push("}"),t}_buildFragmentShaderSource(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,i=[];if(i.push("// Mesh occlusion fragment shader"),i.push("precision lowp float;"),t){i.push("varying vec4 vWorldPosition;");for(var s=0;s<e.sectionPlanes.length;s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("void main(void) {"),t){i.push("  float dist = 0.0;");for(s=0;s<e.sectionPlanes.length;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; }")}return i.push("   gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position")}_buildMarkerList(){for(var e in this._numMarkers=0,this._markers)this._markers.hasOwnProperty(e)&&(this._markerList[this._numMarkers]=this._markers[e],this._markerIndices[e]=this._numMarkers,this._numMarkers++);this._markerList.length=this._numMarkers}_buildPositions(){for(var e=0,t=0;t<this._numMarkers;t++)if(this._markerList[t]){const i=this._markerList[t].worldPos;this._positions[e++]=i[0],this._positions[e++]=i[1],this._positions[e++]=i[2],this._indices[t]=t}this._positions.length=3*this._numMarkers,this._indices.length=this._numMarkers}_buildVBOs(){if(this._positionsBuf){if(this._lenPositionsBuf===this._positions.length)return void this._positionsBuf.setData(this._positions);this._positionsBuf.destroy(),this._positionsBuf=null,this._indicesBuf.destroy(),this._indicesBuf=null}const e=this._scene.canvas.gl,t=3*this._numMarkers,i=this._numMarkers;this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._positions),t,3,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this._indices),i,1,e.STATIC_DRAW),this._lenPositionsBuf=this._positions.length}_buildOcclusionTestList(){const e=this._scene.canvas,t=this._scene.camera.perspective.near;let i,s,r,o,a,n,l=0;const h=e.boundary,c=h[2],d=h[3];for(this._lenOcclusionTestList=0,n=0;n<this._numMarkers;n++)(r=(i=this._markerList[n]).viewPos)[2]>-t?i._setVisible(!1):(o=(s=i.canvasPos)[0],a=s[1],o+10<0||a+10<0||o-10>c||a-10>d?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this._occlusionTestList[this._lenOcclusionTestList++]=i,this._pixels[l++]=o,this._pixels[l++]=a):i._setVisible(!0):i._setVisible(!1))}drawMarkers(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._sectionPlanesState,o=t.camera,a=o._state;if(s.bind(),r.sectionPlanes.length>0){const e=t._sectionPlanesState.sectionPlanes;let s,r,o,a,h;for(var n=0,l=this._uSectionPlanes.length;n<l;n++)r=(s=this._uSectionPlanes[n]).active,o=e[n],r&&i.uniform1i(r,o.active),(a=s.pos)&&i.uniform3fv(s.pos,o.pos),(h=s.dir)&&i.uniform3fv(s.dir,o.dir)}i.uniformMatrix4fv(this._uViewMatrix,!1,a.matrix),i.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.POINTS,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}doOcclusionTest(){{const t=255*MARKER_COLOR[0],i=255*MARKER_COLOR[1],s=255*MARKER_COLOR[2];for(var e=0;e<this._lenOcclusionTestList;e++){const r=this._occlusionTestList[e],o=2*e,a=this._readPixelBuf.read(this._pixels[o],this._pixels[o+1]),n=a[0]===t&&a[1]===i&&a[2]===s;r._setVisible(n)}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){this._markers={},this._markerList.length=0,this._positionsBuf&&this._positionsBuf.destroy(),this._indicesBuf&&this._indicesBuf.destroy(),this._program&&this._program.destroy()}}const tempVec2=math.vec2();class SAOOcclusionRenderer{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Program(e,{vertex:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n                    precision highp float;\n                    precision highp int;\n                    #else\n                    precision mediump float;\n                    precision mediump int;\n                    #endif\n                    \n                    attribute vec3 aPosition;\n                    attribute vec2 aUV;            \n                    varying vec2 vUV;\n                    void main () {\n                        gl_Position = vec4(aPosition, 1.0);\n                        vUV = aUV;\n                    }"],fragment:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n                    precision highp float;\n                    precision highp int;\n                    #else\n                    precision mediump float;\n                    precision mediump int;\n                    #endif\n                    \n                    #extension GL_OES_standard_derivatives : require\n                \n                #define NORMAL_TEXTURE 0\n                #define PI 3.14159265359\n                #define PI2 6.28318530718\n                #define EPSILON 1e-6\n                #define NUM_SAMPLES 7\n                #define NUM_RINGS 4\n\n                precision highp float;\n            \n                varying vec2        vUV;\n            \n                uniform sampler2D   uDepthTexture;\n               \n                uniform float       uCameraNear;\n                uniform float       uCameraFar;\n                uniform mat4        uProjectMatrix;\n                uniform mat4        uInverseProjectMatrix;\n                \n                uniform bool        uPerspective;\n\n                uniform float       uScale;\n                uniform float       uIntensity;\n                uniform float       uBias;\n                uniform float       uKernelRadius;\n                uniform float       uMinResolution;\n                uniform vec2        uViewport;\n                uniform float       uRandomSeed;\n\n                float pow2( const in float x ) { return x*x; }\n                \n                highp float rand( const in vec2 uv ) {\n                    const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n                    highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n                    return fract(sin(sn) * c);\n                }\n\n                vec3 packNormalToRGB( const in vec3 normal ) {\n                    return normalize( normal ) * 0.5 + 0.5;\n                }\n\n                vec3 unpackRGBToNormal( const in vec3 rgb ) {\n                    return 2.0 * rgb.xyz - 1.0;\n                }\n\n                const float packUpscale = 256. / 255.;\n                const float unpackDownScale = 255. / 256.; \n\n                const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\n                const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );   \n\n                const float shiftRights = 1. / 256.;\n\n                vec4 packDepthToRGBA( const in float v ) {\n                    vec4 r = vec4( fract( v * packFactors ), v );\n                    r.yzw -= r.xyz * shiftRights; \n                    return r * packUpscale;\n                }\n\n                float unpackRGBAToDepth( const in vec4 v ) {\n                    return dot( v, unPackFactors );\n                }\n                \n                float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n                    return ( near * far ) / ( ( far - near ) * invClipZ - far );\n                }\n\n                float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n                    return linearClipZ * ( near - far ) - near;\n                }\n                \n                float getDepth( const in vec2 screenPos ) {\n                \treturn unpackRGBAToDepth( texture2D( uDepthTexture, screenPos ) );\n                }\n\n                float getViewZ( const in float depth ) {\n                     if (uPerspective) {\n                         return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n                     } else {\n                        return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n                     }\n                }\n\n                vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n                \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n                \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n                \tclipPosition *= clipW; \n                \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n                }\n\n                vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) {               \n                    return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n                }\n\n                float scaleDividedByCameraFar;\n                float minResolutionMultipliedByCameraFar;\n\n                float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n                \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n                \tfloat viewDistance = length( viewDelta );\n                \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n                \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n                }\n\n                const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n                const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n                float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n            \n                \tscaleDividedByCameraFar = uScale / uCameraFar;\n                \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n                \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n                \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n                \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n                \tvec2 radiusStep = radius;\n\n                \tfloat occlusionSum = 0.0;\n                \tfloat weightSum = 0.0;\n\n                \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n                \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n                \t\tradius += radiusStep;\n                \t\tangle += ANGLE_STEP;\n\n                \t\tfloat sampleDepth = getDepth( sampleUv );\n                \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n                \t\t\tcontinue;\n                \t\t}\n\n                \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n                \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n                \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n                \t\tweightSum += 1.0;\n                \t}\n\n                \tif( weightSum == 0.0 ) discard;\n\n                \treturn occlusionSum * ( uIntensity / weightSum );\n                }\n\n                void main() {\n                \n                \tfloat centerDepth = getDepth( vUV );\n                \t\n                \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n                \t\tdiscard;\n                \t}\n\n                \tfloat centerViewZ = getViewZ( centerDepth );\n                \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n                \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n                \n                \tgl_FragColor = packDepthToRGBA(  1.0- ambientOcclusion );\n                }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",function(){e=!0});const t=math.mat4();return()=>(e&&math.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,a=t.drawingBufferHeight,n=s.camera.project._state,l=n.near,h=n.far,c=n.matrix,d=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;tempVec2[0]=o,tempVec2[1]=a,t.getExtension("OES_standard_derivatives"),t.viewport(0,0,o,a),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,d),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,tempVec2),t.uniform1f(this._uRandomSeed,u),i.bindTexture(this._uDepthTexture,e,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}class SAOBlendRenderer{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._uColorTexture="uColorTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=null,this._aUV=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Program(e,{vertex:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n                    precision highp float;\n                    precision highp int;\n                    #else\n                    precision mediump float;\n                    precision mediump int;\n                    #endif\n                    \n                    attribute   vec3 aPosition;\n                    attribute   vec2 aUV;\n            \n                    varying     vec2 vUV;\n            \n                    void main () {\n                       gl_Position = vec4(aPosition, 1.0);\n                       vUV = aUV;\n                    }"],fragment:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n                    precision highp float;\n                    precision highp int;\n                    #else\n                    precision mediump float;\n                    precision mediump int;\n                    #endif\n                    \n                    \n                    const float packUpscale = 256. / 255.;\n                    const float unpackDownScale = 255. / 256.; \n\n                    const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\n                    const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );   \n\n                    const float shiftRights = 1. / 256.;\n\n                    vec4 packDepthToRGBA( const in float v ) {\n                        vec4 r = vec4( fract( v * packFactors ), v );\n                        r.yzw -= r.xyz * shiftRights; \n                        return r * packUpscale;\n                    }\n                \n                    varying vec2        vUV;\n                    \n                    uniform sampler2D   uColorTexture;\n                    uniform sampler2D   uOcclusionTexture;\n                    \n                    uniform float       uOcclusionScale;\n                    uniform float       uOcclusionCutoff;\n                    \n                    float unpackRGBAToDepth( const in vec4 v ) {\n                        return dot( v, unPackFactors );\n                    }\n                    \n                    void main() {\n                        vec4 color      = texture2D(uColorTexture, vUV);\n                        float ambient   = smoothstep(uOcclusionCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, vUV))) * uOcclusionScale;\n                        gl_FragColor    = vec4(color.rgb * (ambient), color.a);\n                    }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Float32Array([1,1,0,1,0,0,1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._uColorTexture="uColorTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._uOcclusionScale=this._program.getLocation("uOcclusionScale"),this._uOcclusionCutoff=this._program.getLocation("uOcclusionCutoff")}render(e,t){if(this._programError)return;const i=this._scene.canvas.gl,s=this._program,r=i.drawingBufferWidth,o=i.drawingBufferHeight;i.viewport(0,0,r,o),i.clearColor(0,0,0,1),i.disable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT),s.bind(),s.bindTexture(this._uColorTexture,e,0),s.bindTexture(this._uOcclusionTexture,t,2),i.uniform1f(this._uOcclusionScale,1),i.uniform1f(this._uOcclusionCutoff,.01),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}class SAOBlurRenderer{constructor(e){this._scene=e,this._texelOffset=new Float32Array([0,0]),this._program=null,this._programError=!1,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=null,this._aUV=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Program(e,{vertex:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n                    precision highp float;\n                    precision highp int;\n                    #else\n                    precision mediump float;\n                    precision mediump int;\n                    #endif\n                    \n                    attribute   vec3 aPosition;\n                    attribute   vec2 aUV;\n            \n                    varying     vec2 vUV;\n            \n                    void main () {\n                       gl_Position = vec4(aPosition, 1.0);\n                       vUV = aUV;\n                    }"],fragment:["#ifdef GL_FRAGMENT_PRECISION_HIGH\n                    precision highp float;\n                    precision highp int;\n                    #else\n                    precision mediump float;\n                    precision mediump int;\n                    #endif\n                       \n                    varying vec2        vUV;\n                    \n                    uniform sampler2D   uDepthTexture;\n                    uniform sampler2D   uOcclusionTexture;\n                    \n                    uniform float       uOcclusionScale;\n                    uniform float       uOcclusionCutoff;\n                    \n                    uniform vec2        uTexelOffset;\n                    \n                    const float unpackDownScale = 255. / 256.; \n                                   \n                    const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\n                    const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );  \n                \n                    float unpackRGBAToDepth( const in vec4 v ) {\n                        return dot( v, unPackFactors );\n                    }\n                    \n                    const float packUpscale = 256. / 255.;\n       \n                    const float shiftRights = 1. / 256.;\n\n                    vec4 packDepthToRGBA( const in float v ) {\n                        vec4 r = vec4( fract( v * packFactors ), v );\n                        r.yzw -= r.xyz * shiftRights; \n                        return r * packUpscale;\n                    }\n                \n                    void main() {\n                    \n                        float centerOcclusion = unpackRGBAToDepth(texture2D(uOcclusionTexture, vUV));\n                        float centerDepth   = unpackRGBAToDepth(texture2D(uDepthTexture, vUV));\n                        \n                        float gaussian[5];\n                        \n                        gaussian[0] = 0.153170;\n                        gaussian[1] = 0.144893;\n                        gaussian[2] = 0.122649;\n                        gaussian[3] = 0.092902;\n                        gaussian[4] = 0.062970;\n                        \n                        float totalWeight = gaussian[0];\n                        float sum = centerOcclusion * totalWeight;\n            \n                        for (int r = 1; r <= 4; ++r) {\n                            \n                            vec2 uv = vUV + uTexelOffset * float(r) * 2.0;\n                            \n                            float occlusionSample = unpackRGBAToDepth(texture2D(uOcclusionTexture, uv));\n                            float depthSample = unpackRGBAToDepth(texture2D(uDepthTexture, uv));\n                            \n                            float weight = gaussian[r];\n                            weight *= max(0.0, 1.0 - 10.0 * abs(depthSample - centerDepth));\n                            \n                            sum += occlusionSample * weight;\n                            \n                            totalWeight += weight;\n                        }\n                        \n                        for (int r = 1; r <= 4; ++r) {\n                            \n                            vec2 uv = vUV + uTexelOffset * -float(r) * 2.0;\n                            \n                            float occlusionSample = unpackRGBAToDepth(texture2D(uOcclusionTexture, uv));\n                            float depthSample = unpackRGBAToDepth(texture2D(uDepthTexture, uv));\n                            \n                            float weight = gaussian[r];\n                            weight *= max(0.0, 1.0 - 10.0 * abs(depthSample - centerDepth));\n                            \n                            sum += occlusionSample * weight;\n                            \n                            totalWeight += weight;\n                        }\n                     \n                        float blurredOcclusion =  (sum / (totalWeight + 0.0001));\n                     \n                        gl_FragColor = packDepthToRGBA(blurredOcclusion);\n                       \n                    }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Float32Array([1,1,0,1,0,0,1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,t,t.length,3,e.STATIC_DRAW),this._uvBuf=new ArrayBuf(e,e.ARRAY_BUFFER,i,i.length,2,e.STATIC_DRAW),this._indicesBuf=new ArrayBuf(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._uOcclusionScale=this._program.getLocation("uOcclusionScale"),this._uOcclusionCutoff=this._program.getLocation("uOcclusionCutoff"),this._uTexelOffset=this._program.getLocation("uTexelOffset")}render(e,t,i){if(this._programError)return;const s=this._scene.canvas.gl,r=this._program,o=s.drawingBufferWidth,a=s.drawingBufferHeight;0===i?(this._texelOffset[0]=1/o,this._texelOffset[1]=0):(this._texelOffset[0]=0,this._texelOffset[1]=1/a),s.viewport(0,0,o,a),s.clearColor(0,0,0,1),s.disable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT),r.bind(),r.bindTexture(this._uDepthTexture,e,1),r.bindTexture(this._uOcclusionTexture,t,2),s.uniform1f(this._uOcclusionScale,.9),s.uniform1f(this._uOcclusionCutoff,.3),s.uniform2fv(this._uTexelOffset,this._texelOffset),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}const Renderer=function(e,t){t=t||{};const i=new FrameContext,s=e.canvas.canvas,r=e.canvas.gl,o=!!t.transparent,a=t.alphaDepthMask,n=new Map({});var l={},h={};let c=!0,d=!0,u=!0;const p=new RenderBuffer(s,r),m=new RenderBuffer(s,r),_=new RenderBuffer(s,r),g=new RenderBuffer(s,r),f=new RenderBuffer(s,r),v=new SAOOcclusionRenderer(e),b=new SAOBlurRenderer(e),y=new SAOBlendRenderer(e);function M(){c&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){const s=l[e],r=s.drawableMap,o=s.drawableList;var t=0;for(var i in r)r.hasOwnProperty(i)&&(o[t++]=r[i]);o.length=t,s.lenDrawableList=t}}(),c=!1,d=!0),d&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){const t=l[e];t.isStateSortable&&t.drawableList.sort(t.stateSortCompare)}}(),d=!1,u=!0)}this._occlusionTester=null,this.needStateSort=function(){d=!0},this.shadowsDirty=function(){},this.imageDirty=function(){u=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){g.webglContextRestored(e),f.webglContextRestored(e),p.webglContextRestored(e),m.webglContextRestored(e),_.webglContextRestored(e),v.init(),b.init(),y.init(),u=!0},this.addDrawable=function(e,t){var i=t.type;if(i){var s=l[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableList:[],lenDrawableList:0},l[i]=s),s.count++,s.drawableMap[e]=t,h[e]=t,c=!0}else console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring")},this.removeDrawable=function(e){const t=h[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const i=t.type,s=l[i];--s.count<=0?delete l[i]:delete s.drawableMap[e],delete h[e],c=!0},this.getPickID=function(e){return n.addItem(e)},this.putPickID=function(e){n.removeItem(e)},this.clear=function(t){if(t=t||{},r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),o)r.clearColor(0,0,0,0);else{const i=t.ambientColor||e.canvas.backgroundColor||this.lights.getAmbientColor();r.clearColor(i[0],i[1],i[2],1)}r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT|r.STENCIL_BUFFER_BIT)},this.render=function(e){e=e||{},M(),(u||e.force)&&(w(e),stats.frame.frameCount++,u=!1)};const w=function(t){const i=e.sao;i.possible&&(p.bind(),p.clear(),x(t),p.unbind(),m.bind(),m.clear(),v.render(p.getTexture(),null),m.unbind(),i.blur&&(_.bind(),_.clear(),b.render(p.getTexture(),m.getTexture(),0),_.unbind(),m.bind(),m.clear(),b.render(p.getTexture(),_.getTexture(),1),m.unbind())),P(t)},x=function(){const e=new RenderFlags;return function(t){for(var s in WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint&&r.getExtension("OES_element_index_uint"),i.reset(),i.pass=t.pass,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.frontFace(r.CCW),r.enable(r.CULL_FACE),r.depthMask(!0),!1!==t.clear&&r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT|r.STENCIL_BUFFER_BIT),l)if(l.hasOwnProperty(s)){const t=l[s].drawableList;for(let s=0,r=t.length;s<r;s++){const r=t[s];!0!==r.culled&&!1!==r.visible&&r.drawDepth&&(r.getRenderFlags(e),e.normalFillOpaque&&r.drawDepth(i))}}}}(),P=function(){const t=[],s=[],n=[],h=[],c=[],d=[],u=[],p=[],_=[],g=[],f=[],v=[],b=[],y=[],M=[],w=[],x=new RenderFlags;return function(P){WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint&&r.getExtension("OES_element_index_uint");const E=e._lightsState.getAmbientColor();if(i.reset(),i.pass=P.pass,i.withSAO=!1,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),o)r.clearColor(0,0,0,0);else{const t=e.canvas.backgroundColor||E;r.clearColor(t[0],t[1],t[2],1)}r.enable(r.DEPTH_TEST),r.frontFace(r.CCW),r.enable(r.CULL_FACE),r.depthMask(!0),r.lineWidth(1),i.lineWidth=1;const A=e.sao.possible;let C,S,R;i.occlusionTexture=A?m.getTexture():null;const L=Date.now();!1!==P.clear&&r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT|r.STENCIL_BUFFER_BIT);let D=0,k=0,T=0,I=0,B=0,F=0,N=0,V=0,O=0,j=0,U=0,G=0,z=0,H=0,$=0,W=0;for(var X in l)if(l.hasOwnProperty(X)){const e=l[X].drawableList;for(C=0,S=e.length;C<S;C++)!0!==(R=e[C]).culled&&!1!==R.visible&&(R.getRenderFlags(x),x.normalFillOpaque&&(A&&R.saoEnabled?t[D++]=R:R.drawNormalFillOpaque(i)),x.normalEdgesOpaque&&(s[k++]=R),x.normalFillTransparent&&(n[T++]=R),x.normalEdgesTransparent&&(h[I++]=R),x.xrayedFillTransparent&&(u[N++]=R),x.xrayedFillOpaque&&(c[B++]=R),x.xrayedEdgesTransparent&&(p[V++]=R),x.xrayedEdgesOpaque&&(d[F++]=R),x.highlightedFillTransparent&&(f[U++]=R),x.highlightedFillOpaque&&(_[O++]=R),x.highlightedEdgesTransparent&&(v[G++]=R),x.highlightedEdgesOpaque&&(g[j++]=R),x.selectedFillTransparent&&(M[$++]=R),x.selectedFillOpaque&&(b[z++]=R),x.selectedEdgesTransparent&&(w[W++]=R),x.selectedEdgesOpaque&&(y[H++]=R))}if(D>0)for(i.withSAO=!0,C=0;C<D;C++)t[C].drawNormalFillOpaque(i);if(k>0)for(C=0;C<k;C++)s[C].drawNormalEdgesOpaque(i);if(B>0)for(C=0;C<B;C++)c[C].drawXRayedFillOpaque(i);if(F>0)for(C=0;C<F;C++)d[C].drawXRayedEdgesOpaque(i);if(N>0||V>0||T>0){if(r.enable(r.CULL_FACE),r.enable(r.BLEND),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),i.backfaces=!1,a||r.depthMask(!1),V>0)for(C=0;C<V;C++)p[C].drawXRayedEdgesTransparent(i);if(N>0)for(C=0;C<N;C++)u[C].drawXRayedFillTransparent(i);if(T>0)for(C=0;C<T;C++)(R=n[C]).drawNormalFillTransparent(i);if(I>0)for(C=0;C<I;C++)(R=h[C]).drawNormalEdgesTransparent(i);r.disable(r.BLEND),a||r.depthMask(!0)}if(O>0||j>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),j>0)for(C=0;C<j;C++)g[C].drawHighlightedEdgesOpaque(i);if(O>0)for(C=0;C<O;C++)_[C].drawHighlightedFillOpaque(i)}if(U>0||G>0||O>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),G>0)for(C=0;C<G;C++)v[C].drawHighlightedEdgesTransparent(i);if(U>0)for(C=0;C<U;C++)f[C].drawHighlightedFillTransparent(i);r.disable(r.BLEND)}if(z>0||H>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),H>0)for(C=0;C<H;C++)y[C].drawSelectedEdgesOpaque(i);if(z>0)for(C=0;C<z;C++)b[C].drawSelectedFillOpaque(i)}if($>0||W>0){if(i.lastProgramId=null,r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),o?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),W>0)for(C=0;C<W;C++)w[C].drawSelectedEdgesTransparent(i);if($>0)for(C=0;C<$;C++)M[C].drawSelectedFillTransparent(i);r.disable(r.BLEND)}const Y=Date.now(),q=stats.frame;q.renderTime=(Y-L)/1e3,q.drawElements=i.drawElements,q.drawElements=i.drawElements,q.useProgram=i.useProgram,q.bindTexture=i.bindTexture,q.bindArray=i.bindArray;const K=WEBGL_INFO.MAX_TEXTURE_UNITS;for(let e=0;e<K;e++)r.activeTexture(r.TEXTURE0+e);r.bindTexture(r.TEXTURE_CUBE_MAP,null),r.bindTexture(r.TEXTURE_2D,null);const Z=WEBGL_INFO.MAX_VERTEX_ATTRIBS;for(let e=0;e<Z;e++)r.disableVertexAttribArray(e)}}();this.pick=function(){const t=math.vec3(),o=math.mat4(),a=math.vec3([0,1,0]),h=math.frustumMat4(-1,1,-1,1,.1,1e4),c=new PickResult;return function(d,u=c){let p,m,_,f,v;u.reset(),M(),WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint&&r.getExtension("OES_element_index_uint");let b=null,y=null;u.pickSurface=d.pickSurface,d.canvasPos?(p=d.canvasPos[0],m=d.canvasPos[1],b=e.camera.viewMatrix,y=e.camera.projMatrix,u.canvasPos=d.canvasPos):(d.matrix?(b=d.matrix,y=h):(_=d.origin||math.vec3([0,0,0]),f=d.direction||math.vec3([0,0,1]),v=math.addVec3(_,f,t),b=math.lookAtMat4v(_,v,a,o),y=h,u.origin=_,u.direction=f),p=.5*s.clientWidth,m=.5*s.clientHeight),g.bind();const w=function(e,t,s,o,a){let h,c;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickViewMatrix=s,i.pickProjMatrix=o,i.pickInvisible=!!a.pickInvisible,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.enable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT);const d=a.includeEntityIds,u=a.excludeEntityIds;for(var p in l)if(l.hasOwnProperty(p)){const e=l[p],t=e.drawableList;for(h=0,c=t.length;h<c;h++){const e=t[h];!e.drawPickMesh||!0===e.culled||!0!==a.pickInvisible&&!1===e.visible||!1===e.pickable||(d&&!d[e.id]||u&&u[e.id]||e.drawPickMesh(i))}}const m=g.read(Math.round(e),Math.round(t));let _=m[0]+256*m[1]+256*m[2]*256+256*m[3]*256*256;if(_<0)return;return n.items[_]}(p,m,b,y,d);return w?(d.pickSurface&&(w.canPickTriangle&&w.canPickTriangle()?(!function(e,t,s,o,a,n){if(!e.drawPickTriangles)return;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickViewMatrix=o,i.pickProjMatrix=a,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.enable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),e.drawPickTriangles(i);const l=g.read(t,s);let h=l[0]+256*l[1]+256*l[2]*256+256*l[3]*256*256;h*=3,n.primIndex=h}(w,p,m,b,y,u),w.pickTriangleSurface(b,y,u)):w.canPickWorldPos&&w.canPickWorldPos()&&(E(w,p,m,b,y,u),function(e,t,s,o,a,n){i.reset(),i.backfaces=!0,i.frontface=!0,i.pickViewMatrix=o,i.pickProjMatrix=a,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.enable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),e.drawPickNormals(i);const l=g.read(Math.round(t),Math.round(s)),h=[l[0]/256-.5,l[1]/256-.5,l[2]/256-.5];math.normalizeVec3(h),n.worldNormal=h}(w,p,m,b,y,u))),g.unbind(),u.entity=w.delegatePickedEntity?w.delegatePickedEntity():w,u):(g.unbind(),null)}}();var E=function(){const e=math.vec4(),t=math.vec4(),o=math.vec4(),a=math.vec4(),n=math.vec4(),l=math.mat4(),h=math.mat4();return function(c,d,u,p,m,_){i.reset(),i.backfaces=!0,i.frontface=!0,i.pickViewMatrix=p,i.pickProjMatrix=m,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.enable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),c.drawPickDepths(i);const f=g.read(Math.round(d),Math.round(u)),v=(y=[(b=f)[0]/256,b[1]/256,b[2]/256,b[3]/256],math.dotVec4(y,[1/16777216,1/65536,1/256,1]));var b,y,M=(d-s.width/2)/(s.width/2),w=-(u-s.height/2)/(s.height/2),x=math.mulMat4(m,p,l),P=math.inverseMat4(x,h);e[0]=M,e[1]=w,e[2]=-1,e[3]=1;var E=math.transformVec4(P,e);E=math.mulVec4Scalar(E,1/E[3]),t[0]=M,t[1]=w,t[2]=1,t[3]=1;var A=math.transformVec4(P,t);A=math.mulVec4Scalar(A,1/A[3]);var C=math.subVec3(A,E,o),S=math.addVec3(E,math.mulVec4Scalar(C,v,a),n);_.worldPos=S}}();this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new OcclusionTester(e),this._occlusionTester.addMarker(t)},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester){for(var e in M(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.frontface=!0,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.enable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(e)){const r=l[e].drawableList;for(var t=0,s=r.length;t<s;t++){const e=r[t];e.drawOcclusion&&!0!==e.culled&&!1!==e.visible&&!1!==e.pickable&&e.drawOcclusion(i)}}this._occlusionTester.drawMarkers(i),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,s){let r,o,a,n;for(f.bind(),f.clear(),this.render({force:!0,opaqueOnly:s}),o=0;o<i;o++)a=2*o,n=4*o,r=f.read(e[a],e[a+1]),t[n]=r[0],t[n+1]=r[1],t[n+2]=r[2],t[n+3]=r[3];f.unbind(),u=!0},this.readImage=function(e){f.bind(),f.clear(),this.render({force:!0,opaqueOnly:!1});const t=f.readImage(e);return f.unbind(),u=!0,t},this.destroy=function(){l={},h={},g.destroy(),f.destroy(),p.destroy(),m.destroy(),_.destroy(),v.destroy(),b.destroy(),y.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class Input extends Component{constructor(e,t={}){super(e,t),this.KEY_BACKSPACE=8,this.KEY_TAB=9,this.KEY_ENTER=13,this.KEY_SHIFT=16,this.KEY_CTRL=17,this.KEY_ALT=18,this.KEY_PAUSE_BREAK=19,this.KEY_CAPS_LOCK=20,this.KEY_ESCAPE=27,this.KEY_PAGE_UP=33,this.KEY_PAGE_DOWN=34,this.KEY_END=35,this.KEY_HOME=36,this.KEY_LEFT_ARROW=37,this.KEY_UP_ARROW=38,this.KEY_RIGHT_ARROW=39,this.KEY_DOWN_ARROW=40,this.KEY_INSERT=45,this.KEY_DELETE=46,this.KEY_NUM_0=48,this.KEY_NUM_1=49,this.KEY_NUM_2=50,this.KEY_NUM_3=51,this.KEY_NUM_4=52,this.KEY_NUM_5=53,this.KEY_NUM_6=54,this.KEY_NUM_7=55,this.KEY_NUM_8=56,this.KEY_NUM_9=57,this.KEY_A=65,this.KEY_B=66,this.KEY_C=67,this.KEY_D=68,this.KEY_E=69,this.KEY_F=70,this.KEY_G=71,this.KEY_H=72,this.KEY_I=73,this.KEY_J=74,this.KEY_K=75,this.KEY_L=76,this.KEY_M=77,this.KEY_N=78,this.KEY_O=79,this.KEY_P=80,this.KEY_Q=81,this.KEY_R=82,this.KEY_S=83,this.KEY_T=84,this.KEY_U=85,this.KEY_V=86,this.KEY_W=87,this.KEY_X=88,this.KEY_Y=89,this.KEY_Z=90,this.KEY_LEFT_WINDOW=91,this.KEY_RIGHT_WINDOW=92,this.KEY_SELECT_KEY=93,this.KEY_NUMPAD_0=96,this.KEY_NUMPAD_1=97,this.KEY_NUMPAD_2=98,this.KEY_NUMPAD_3=99,this.KEY_NUMPAD_4=100,this.KEY_NUMPAD_5=101,this.KEY_NUMPAD_6=102,this.KEY_NUMPAD_7=103,this.KEY_NUMPAD_8=104,this.KEY_NUMPAD_9=105,this.KEY_MULTIPLY=106,this.KEY_ADD=107,this.KEY_SUBTRACT=109,this.KEY_DECIMAL_POINT=110,this.KEY_DIVIDE=111,this.KEY_F1=112,this.KEY_F2=113,this.KEY_F3=114,this.KEY_F4=115,this.KEY_F5=116,this.KEY_F6=117,this.KEY_F7=118,this.KEY_F8=119,this.KEY_F9=120,this.KEY_F10=121,this.KEY_F11=122,this.KEY_F12=123,this.KEY_NUM_LOCK=144,this.KEY_SCROLL_LOCK=145,this.KEY_SEMI_COLON=186,this.KEY_EQUAL_SIGN=187,this.KEY_COMMA=188,this.KEY_DASH=189,this.KEY_PERIOD=190,this.KEY_FORWARD_SLASH=191,this.KEY_GRAVE_ACCENT=192,this.KEY_OPEN_BRACKET=219,this.KEY_BACK_SLASH=220,this.KEY_CLOSE_BRACKET=221,this.KEY_SINGLE_QUOTE=222,this.KEY_SPACE=32,this.element=t.element,this.altDown=!1,this.ctrlDown=!1,this.mouseDownLeft=!1,this.mouseDownMiddle=!1,this.mouseDownRight=!1,this.keyDown=[],this.enabled=!0,this.keyboardEnabled=!0,this.mouseover=!1,this.mouseCanvasPos=math.vec2(),this._bindEvents()}_bindEvents(){if(!this._eventsBound){document.addEventListener("keydown",this._keyDownListener=(e=>{this.enabled&&this.keyboardEnabled&&("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0)),this.mouseover&&e.preventDefault())}),!1),document.addEventListener("keyup",this._keyUpListener=(e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))})),this.element.addEventListener("mouseenter",this._mouseEnterListener=(e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))})),this.element.addEventListener("mouseleave",this._mouseLeaveListener=(e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))})),this.element.addEventListener("mousedown",this._mouseDownListener=(e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}})),document.addEventListener("mouseup",this._mouseUpListener=(e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}}),!0),document.addEventListener("click",this._clickListener=(e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}})),document.addEventListener("dblclick",this._dblClickListener=(e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}})),this.element.addEventListener("mousemove",this._mouseMoveListener=(e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())})),this.element.addEventListener("wheel",this._mouseWheelListener=((e,t)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",i,!0)}),{passive:!0});{let e,t;const i=2;this.on("mousedown",i=>{e=i[0],t=i[1]}),this.on("mouseup",s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)})}{const e={"landscape-primary":90,"landscape-secondary":-90,"portrait-secondary":180,"portrait-primary":0};let t,i;const s=math.vec3(),r=math.vec3(),o={orientation:null,orientationAngle:0},a={orientationAngle:0,acceleration:null,accelerationIncludingGravity:r,rotationRate:math.vec3(),interval:0},n={alpha:0,beta:0,gamma:0,absolute:!1};window.OrientationChangeEvent&&window.addEventListener("orientationchange",this._orientationchangedListener=(()=>{t=window.screen.orientation||window.screen.mozOrientation||window.msOrientation||null,i=t&&e[t]||0,o.orientation=t,o.orientationAngle=i,this.fire("orientationchange",o)}),!1),window.DeviceMotionEvent&&window.addEventListener("devicemotion",this._deviceMotionListener=(e=>{a.interval=e.interval,a.orientationAngle=i;const t=e.acceleration;t?(s[0]=t.x,s[1]=t.y,s[2]=t.z,a.acceleration=s):a.acceleration=null;const o=e.accelerationIncludingGravity;o?(r[0]=o.x,r[1]=o.y,r[2]=o.z,a.accelerationIncludingGravity=r):a.accelerationIncludingGravity=null,a.rotationRate=e.rotationRate,this.fire("devicemotion",a)}),!1),window.DeviceOrientationEvent&&window.addEventListener("deviceorientation",this._deviceOrientListener=(e=>{n.gamma=e.gamma,n.beta=e.beta,n.alpha=e.alpha,n.absolute=e.absolute,this.fire("deviceorientation",n)}),!1)}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(document.removeEventListener("keydown",this._keyDownListener),document.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}class Viewport extends Component{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new RenderState({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)},this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class Perspective extends Component{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:2e3}),this._dirty=!1,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.viewport.boundary,t=e[2]/e[3];let i=this._fov;const s=this._fovAxis;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),math.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set fov(e){this._fov=void 0!==e&&null!==e?e:60,this._needUpdate(0),this.fire("fov",this._fov)}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=void 0!==e&&null!==e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=void 0!==e&&null!==e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}destroy(){super.destroy(),this._state.destroy(),super.destroy(),this.scene.canvas.off(this._canvasResized)}}class Ortho extends Component{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:2e3}),this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.viewport.boundary,s=i[2],r=i[3],o=s/r;let a,n,l,h;s>r?(a=-t,n=t,l=t/o,h=-t/o):(a=-t*o,n=t*o,l=t,h=-t),math.orthoMat4c(a,n,h,l,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){void 0!==e&&null!==e||(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=void 0!==e&&null!==e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=void 0!==e&&null!==e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class Frustum extends Component{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){math.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=void 0!==e&&null!==e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=void 0!==e&&null!==e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=void 0!==e&&null!==e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=void 0!==e&&null!==e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=void 0!==e&&null!==e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=void 0!==e&&null!==e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class CustomProjection extends Component{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this._state=new RenderState({matrix:math.mat4()}),this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this.glRedraw(),this.fire("far",this._state.matrix)}get matrix(){return this._state.matrix}destroy(){super.destroy(),this._state.destroy()}}const tempVec3$1=math.vec3(),tempVec3b=math.vec3(),tempVec3c=math.vec3(),tempVec3d=math.vec3(),tempVec3e=math.vec3(),tempVec3f=math.vec3(),tempMat=math.mat4(),tempMatb=math.mat4(),eyeLookVec=math.vec3(),eyeLookVecNorm=math.vec3(),eyeLookOffset=math.vec3(),offsetEye=math.vec3();class Camera extends Component{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new RenderState({deviceMatrix:math.mat4(),hasDeviceMatrix:!1,matrix:math.mat4(),normalMatrix:math.mat4()}),this._perspective=new Perspective(this),this._ortho=new Ortho(this),this._frustum=new Frustum(this),this._customProjection=new CustomProjection(this),this._project=this._perspective,this._eye=math.vec3([0,0,10]),this._look=math.vec3([0,0,0]),this._up=math.vec3([0,1,0]),this._worldUp=math.vec3([0,1,0]),this._worldRight=math.vec3([1,0,0]),this._worldForward=math.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)}),this._ortho.on("matrix",()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)}),this._frustum.on("matrix",()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)}),this._customProjection.on("matrix",()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)})}_update(){const e=this._state;let t;"ortho"===this.projection?(math.subVec3(this._eye,this._look,eyeLookVec),math.normalizeVec3(eyeLookVec,eyeLookVecNorm),math.mulVec3Scalar(eyeLookVecNorm,1e3,eyeLookOffset),math.addVec3(this._look,eyeLookOffset,offsetEye),t=offsetEye):t=this._eye,e.hasDeviceMatrix?(math.lookAtMat4v(t,this._look,this._up,tempMatb),math.mulMat4(e.deviceMatrix,tempMatb,e.matrix)):math.lookAtMat4v(t,this._look,this._up,e.matrix),math.inverseMat4(this._state.matrix,this._state.normalMatrix),math.transposeMat4(this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=math.subVec3(this._eye,this._look,tempVec3$1);math.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tempMat),t=math.transformPoint3(tempMat,t,tempVec3b),this.eye=math.addVec3(this._look,t,tempVec3c),this.up=math.transformPoint3(tempMat,this._up,tempVec3d)}orbitPitch(e){if(this._constrainPitch&&(e=math.dotVec3(this._up,this._worldUp)/math.DEGTORAD)<1)return;let t=math.subVec3(this._eye,this._look,tempVec3$1);const i=math.cross3Vec3(math.normalizeVec3(t,tempVec3b),math.normalizeVec3(this._up,tempVec3c));math.rotationMat4v(.0174532925*e,i,tempMat),t=math.transformPoint3(tempMat,t,tempVec3d),this.up=math.transformPoint3(tempMat,this._up,tempVec3e),this.eye=math.addVec3(t,this._look,tempVec3f)}yaw(e){let t=math.subVec3(this._look,this._eye,tempVec3$1);math.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tempMat),t=math.transformPoint3(tempMat,t,tempVec3b),this.look=math.addVec3(t,this._eye,tempVec3c),this._gimbalLock&&(this.up=math.transformPoint3(tempMat,this._up,tempVec3d))}pitch(e){if(this._constrainPitch&&(e=math.dotVec3(this._up,this._worldUp)/math.DEGTORAD)<1)return;let t=math.subVec3(this._look,this._eye,tempVec3$1);const i=math.cross3Vec3(math.normalizeVec3(t,tempVec3b),math.normalizeVec3(this._up,tempVec3c));math.rotationMat4v(.0174532925*e,i,tempMat),this.up=math.transformPoint3(tempMat,this._up,tempVec3f),t=math.transformPoint3(tempMat,t,tempVec3d),this.look=math.addVec3(t,this._eye,tempVec3e)}pan(e){const t=math.subVec3(this._eye,this._look,tempVec3$1),i=[0,0,0];let s;if(0!==e[0]){const r=math.cross3Vec3(math.normalizeVec3(t,[]),math.normalizeVec3(this._up,tempVec3b));s=math.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=math.mulVec3Scalar(math.normalizeVec3(this._up,tempVec3c),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=math.mulVec3Scalar(math.normalizeVec3(t,tempVec3d),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=math.addVec3(this._eye,i,tempVec3e),this.look=math.addVec3(this._look,i,tempVec3f)}zoom(e){const t=math.subVec3(this._eye,this._look,tempVec3$1),i=Math.abs(math.lenVec3(t,tempVec3b)),s=Math.abs(i+e);if(s<.5)return;const r=math.normalizeVec3(t,tempVec3c);this.eye=math.addVec3(this._look,math.mulVec3Scalar(r,s),tempVec3d)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=new Float32Array(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return math.lenVec3(math.subVec3(this._look,this._eye,tempVec3$1))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}destroy(){super.destroy(),this._state.destroy()}}class Light extends Component{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class DirLight extends Light{get type(){return"DirLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0,this._state=new RenderState({type:"dir",dir:math.vec3([1,1,1]),color:math.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,shadowDirty:!0,getShadowViewMatrix:function(){math.vec3();const e=math.vec3([0,1,0]);return function(){if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=math.identityMat4());const t=i._state.dir;math.lookAtMat4v([-t[0],-t[1],-t[2]],[0,0,0],e,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix}}(),getShadowProjMatrix:function(){return i._shadowProjMatrixDirty&&(i._shadowProjMatrix||(i._shadowProjMatrix=math.identityMat4()),math.orthoMat4c(-10,10,-10,10,0,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1),i._shadowProjMatrix},getShadowRenderBuf:function(){return i._shadowRenderBuf||(i._shadowRenderBuf=new RenderBuffer(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf}}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class AmbientLight extends Light{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:math.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy()}}const PRESETS$1={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 EdgeMaterial extends Material{get type(){return"EdgeMaterial"}get presets(){return PRESETS$1}constructor(e,t={}){super(e,t),this._state=new RenderState({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=void 0!==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=PRESETS$1[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(PRESETS$1).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const unitsInfo={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class Metrics extends Component{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=math.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return unitsInfo}set units(e){e||(e="meters"),unitsInfo[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=new Float32Array(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=new Float32Array(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class SAO extends Component{constructor(e,t={}){super(e,t),this._supported=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.scene._needRecompile=!0,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){void 0!==e&&null!==e||(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){void 0!==e&&null!==e||(e=.25),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){void 0!==e&&null!==e||(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){void 0!==e&&null!==e||(e=500),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){void 0!==e&&null!==e||(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){void 0!==e&&null!==e||(e=.2),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){void 0!==e&&null!==e||(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}function getEntityIDMap(e,t){const i={};let s,r;for(let o=0,a=t.length;o<a;o++)s=t[o],(r=e.component[s])?r.isEntity?i[s]=!0:e.warn("pick(): Component is not an Entity: "+s):e.warn("pick(): Component not found: "+s);return i}class Scene extends Component{get type(){return"Scene"}constructor(e={}){super(null,e);const t=e.canvasElement||document.getElementById(e.canvasId);if(!(t instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";const i=!!e.transparent,s=!!e.alphaDepthMask;this._aabbDirty=!0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.realWorldOffset=e.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new Canvas(this,{dontClear:!0,canvas:t,spinnerElementId:e.spinnerElementId,transparent:i,backgroundColor:e.backgroundColor,webgl2:!1!==e.webgl2,contextAttr:e.contextAttr||{},clearColorAmbient:e.clearColorAmbient,premultipliedAlpha:e.premultipliedAlpha}),this.canvas.on("boundary",()=>{this.glRedraw()}),this.canvas.on("webglContextFailed",()=>{alert("xeokit failed to find WebGL!")}),this._renderer=new Renderer(this,{transparent:i,alphaDepthMask:s}),this._sectionPlanesState=new function(){this.sectionPlanes=[];let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";let i;const s=[];for(let e=0,r=t.length;e<r;e++)i=t[e],s.push("cp");return s.push(";"),e=s.join("")},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let i=0,s=this.sectionPlanes.length;i<s;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)}},this._lightsState=new function(){const e=math.vec3([0,0,0]),t=math.vec3();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i<r;i++)s=t[i],e.push("/"),e.push(s.type),e.push("world"===s.space?"w":"v"),s.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join("")},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t<r;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),s&&s.id===e.id&&(s=null),void(i=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(let t=0,s=this.reflectionMaps.length;t<s;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(let t=0,s=this.lightMaps.length;t<s;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColor=function(){if(!s)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){s=t;break}}if(s){const e=s.color,i=s.intensity;return t[0]=e[0]*i,t[1]=e[1]*i,t[2]=e[2]*i,t}return e}},this.input=new Input(this,{dontClear:!0,element:this.canvas.canvas}),this.metrics=new Metrics(this,{units:e.units,scale:e.scale,origin:e.origin}),this.sao=new SAO(this,{enabled:e.saoEnabled}),this.ticksPerRender=e.ticksPerRender,this.ticksPerOcclusionTest=e.ticksPerOcclusionTest,this.passes=e.passes,this.clearEachPass=e.clearEachPass,this.gammaInput=e.gammaInput,this.gammaOutput=e.gammaOutput,this.gammaFactor=e.gammaFactor,core._addScene(this),this._initDefaults(),this._viewport=new Viewport(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new Camera(this,{id:"default.camera",dontClear:!0}),new AmbientLight(this,{color:[.3,.3,.3],intensity:.7}),new DirLight(this,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:.9,space:"view"}),new DirLight(this,{dir:[-.8,-.4,-.4],color:[1,1,1],intensity:.9,space:"view"}),new DirLight(this,{dir:[.2,-.8,.8],color:[.7,.7,.7],intensity:.9,space:"view"}),this._camera.on("dirty",()=>{this._renderer.imageDirty()})}_initDefaults(){let e;e=this.geometry,e=this.material,e=this.xrayMaterial,e=this.edgeMaterial,e=this.selectedMaterial,e=this.highlightMaterial}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+utils.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=math.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],utils.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){delete this.models[e.id],this._modelIds=null}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_objectSelectedUpdated(e){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&core.runTasks();const t={sceneId:null,pass:0};this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;r<i;r++)t.pass=r,this.fire("rendering",t,!0),o=s||0===r,this._renderer.render({pass:r,clear:o,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColor();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=math.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}set ticksPerRender(e){void 0===e||null===e?e=1:(!utils.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){void 0===e||null===e?e=20:(!utils.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){void 0===e||null===e?e=1:(!utils.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0)}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!1!==e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0)}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=void 0===e||null===e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||buildBoxGeometry(ReadableGeometry)}get material(){return this.components["default.material"]||new PhongMaterial(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new EmphasisMaterial(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new EmphasisMaterial(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new EmphasisMaterial(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new EdgeMaterial(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=math.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=math.AABB3());let e,t=math.MAX_DOUBLE,i=math.MAX_DOUBLE,s=math.MAX_DOUBLE,r=-math.MAX_DOUBLE,o=-math.MAX_DOUBLE,a=-math.MAX_DOUBLE;const n=this._collidables;let l,h=!1;for(const c in n)if(n.hasOwnProperty(c)){if(!1===(l=n[c]).collidable)continue;(e=l.aabb)[0]<t&&(t=e[0]),e[1]<i&&(i=e[1]),e[2]<s&&(s=e[2]),e[3]>r&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),h=!0}h||(t=-100,i=-100,s=-100,r=100,o=100,a=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=getEntityIDMap(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=getEntityIDMap(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity.fire&&t.entity.fire("picked",t),t):void 0}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t<i;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(utils.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,i=1e5,s=1e5,r=1e5,o=-1e5,a=-1e5,n=-1e5;if(this._withEntities(e,this.objects,e=>{if(e.collidable){const l=e.aabb;l[0]<i&&(i=l[0]),l[1]<s&&(s=l[1]),l[2]<r&&(r=l[2]),l[3]>o&&(o=l[3]),l[4]>a&&(a=l[4]),l[5]>n&&(n=l[5]),t=!0}}),t){const e=math.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=a,e[5]=n,e}return this.aabb}setObjectsVisible(e,t){return this._withEntities(e,this.objects,e=>{const i=e.visible!==t;return e.visible=t,i})}setObjectsCollidable(e,t){return this._withEntities(e,this.objects,e=>{const i=e.collidable!==t;return e.collidable=t,i})}setObjectsCulled(e,t){return this._withEntities(e,this.objects,e=>{const i=e.culled!==t;return e.culled=t,i})}setObjectsSelected(e,t){return this._withEntities(e,this.objects,e=>{const i=e.selected!==t;return e.selected=t,i})}setObjectsHighlighted(e,t){return this._withEntities(e,this.objects,e=>{const i=e.highlighted!==t;return e.highlighted=t,i})}setObjectsXRayed(e,t){return this._withEntities(e,this.objects,e=>{const i=e.xrayed!==t;return e.xrayed=t,i})}setObjectsEdges(e,t){return this._withEntities(e,this.objects,e=>{const i=e.edges!==t;return e.edges=t,i})}setObjectsColorized(e,t){return this._withEntities(e,this.objects,e=>{e.colorize=t})}setObjectsOpacity(e,t){return this._withEntities(e,this.objects,e=>{const i=e.opacity!==t;return e.opacity=t,i})}setObjectsPickable(e,t){return this._withEntities(e,this.objects,e=>{const i=e.pickable!==t;return e.pickable=t,i})}_withEntities(e,t,i){utils.isString(e)&&(e=[e]);let s=!1;for(let r=0,o=e.length;r<o;r++){let o=t[e[r]];o&&(s=i(o)||s)}return s}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}class Plane{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new Mesh(t,{id:i.id,geometry:new ReadableGeometry(t,buildBoxGeometry({xSize:.5,ySize:.5,zSize:.001})),material:new PhongMaterial(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new EdgeMaterial(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new EmphasisMaterial(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new EmphasisMaterial(t,{fill:!0,fillColor:[0,0,1],fillAlpha:.7,edges:!0,edgeColor:[1,0,0],edgeAlpha:1,edgeWidth:1}),highlighted:!0,scale:[3,3,3],position:[0,0,0],rotation:[0,0,0],opacity:.3,edges:!0});{const e=math.vec3([0,0,0]),t=math.vec3(),i=math.vec3([0,0,1]),s=math.vec4(4),r=math.vec3(),o=()=>{const o=this._sectionPlane.scene.center,a=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];math.subVec3(o,this._sectionPlane.pos,e);const n=-math.dotVec3(a,e);math.normalizeVec3(a),math.mulVec3Scalar(a,n,t);const l=math.vec3PairToQuaternion(i,this._sectionPlane.dir,s);r[0]=.1*t[0],r[1]=.1*t[1],r[2]=.1*t[2],this._mesh.quaternion=l,this._mesh.position=r};this._onSectionPlanePos=this._sectionPlane.on("pos",o),this._onSectionPlaneDir=this._sectionPlane.on("dir",o)}this._highlighted=!1,this._selected=!1}setHighlighted(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}getHighlighted(){return this._highlighted}setSelected(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}getSelected(){return this._selected}destroy(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}class Overview{constructor(e,t){if(!(t.onHoverEnterPlane&&t.onHoverLeavePlane&&t.onClickedNothing&&t.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=e,this._viewer=e.viewer,this._onHoverEnterPlane=t.onHoverEnterPlane,this._onHoverLeavePlane=t.onHoverLeavePlane,this._onClickedNothing=t.onClickedNothing,this._onClickedPlane=t.onClickedPlane,this._visible=!0,this._planes={},this._canvas=t.overviewCanvas,this._scene=new Scene({canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new DirLight(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new DirLight(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new DirLight(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;{const e=this._scene.camera,t=math.rotationMat4c(-90*math.DEGTORAD,1,0,0),i=math.vec3(),s=math.vec3(),r=math.vec3();this._synchCamera=(()=>{const o=this._viewer.camera.eye,a=this._viewer.camera.look,n=this._viewer.camera.up;math.mulVec3Scalar(math.normalizeVec3(math.subVec3(o,a,i)),7),this._zUp?(math.transformVec3(t,i,s),math.transformVec3(t,n,r),e.look=[0,0,0],e.eye=math.transformVec3(t,i,s),e.up=math.transformPoint3(t,n,r)):(e.look=[0,0,0],e.eye=i,e.up=n)})}this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",e=>{this._scene.camera.perspective.fov=e}),this._onViewerCameraProjection=this._viewer.camera.on("projection",e=>{this._scene.camera.projection=e});var i=null;this._onInputMouseMove=this._scene.input.on("mousemove",e=>{const t=this._scene.pick({canvasPos:e});if(t){if(!i||t.entity.id!==i.id){if(i){this._planes[i.id]&&this._onHoverLeavePlane(i.id)}i=t.entity,this._planes[i.id]&&this._onHoverEnterPlane(i.id)}}else i&&(this._onHoverLeavePlane(i.id),i=null)}),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=(()=>{if(i){this._planes[i.id]&&this._onClickedPlane(i.id)}else this._onClickedNothing()})),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=(()=>{i&&(this._onHoverLeavePlane(i.id),i=null)})),this.setVisible(t.overviewVisible)}addSectionPlane(e){this._planes[e.id]=new Plane(this,this._scene,e)}setPlaneHighlighted(e,t){const i=this._planes[e];i&&i.setHighlighted(t)}setPlaneSelected(e,t){const i=this._planes[e];i&&i.setSelected(t)}removeSectionPlane(e){const t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}setVisible(e=!0){this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}getVisible(){return this._visible}destroy(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._viewer.camera.off(this._onViewerCameraProjection),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}const tempAABB$1=math.AABB3(),tempVec3$2=math.vec3();class SectionPlanesPlugin extends Plugin{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);if(!e)return void this.error("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview");this._overview=new Overview(this,{overviewCanvas:e,visible:t.overviewVisible,onHoverEnterPlane:e=>{this._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:e=>{this._overview.setPlaneHighlighted(e,!1)},onClickedPlane:e=>{if(this.getShownControl()===e)return void this.hideControl();this.showControl(e);const t=this.sectionPlanes[e].pos;tempAABB$1.set(this.viewer.scene.aabb),math.getAABB3Center(tempAABB$1,tempVec3$2),tempAABB$1[0]+=t[0]-tempVec3$2[0],tempAABB$1[1]+=t[1]-tempVec3$2[1],tempAABB$1[2]+=t[2]-tempVec3$2[2],tempAABB$1[3]+=t[0]-tempVec3$2[0],tempAABB$1[4]+=t[1]-tempVec3$2[1],tempAABB$1[5]+=t[2]-tempVec3$2[2],this.viewer.cameraFlight.flyTo({aabb:tempAABB$1,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}})}else this.error("Config missing: overviewCanvasId - will create plugin without overview");this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",e=>{this._sectionPlaneCreated(e)})}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){return void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),new SectionPlane(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0})}_sectionPlaneCreated(e){const t=this._freeControls.length>0?this._freeControls.pop():new Control(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",()=>{this._sectionPlaneDestroyed(e)})}showControl(e){const t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}getShownControl(){return this._shownControlId}hideControl(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}destroySectionPlane(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}_sectionPlaneDestroyed(e){this._overview&&this._overview.removeSectionPlane(e);const t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}clear(){const e=Object.keys(this._sectionPlanes);for(var t=0,i=e.length;t<i;t++)this.destroySectionPlane(e[t])}send(e,t){switch(e){case"snapshotStarting":for(let e in this._controls)this._controls.hasOwnProperty(e)&&this._controls[e].setCulled(!0);break;case"snapshotFinished":for(let e in this._controls)this._controls.hasOwnProperty(e)&&this._controls[e].setCulled(!1);break;case"clearSectionPlanes":this.clear()}}destroy(){this.clear(),this._overview&&this._overview.destroy(),this._destroyFreeControls(),super.destroy()}_destroyFreeControls(){for(var e=this._freeControls.pop();e;)e._destroy(),e=this._freeControls.pop();this.viewer.scene.off(this._onSceneSectionPlaneCreated)}}const idMap=new Map;class ContextMenu{constructor(e={}){this._id=idMap.addItem(),this._context=null,this._menuElement=null,this._enabled=!1,this._items=[],document.addEventListener("mousedown",e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()}),e.items&&(this.items=e.items),this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}set items(e){this._items=e||[],this._menuElement&&(this._menuElement.parentElement.removeChild(this._menuElement),this._menuElement=null);const t=[],i="xeokit-context-menu-"+this._id;t.push('<div class="xeokit-context-menu '+i+'" style="z-index:300000; position: absolute;">'),t.push("<ul>"),this._buildActionLinks(this._items,t),t.push("</ul>"),t.push("</div>");const s=t.join("");document.body.insertAdjacentHTML("beforeend",s),this._menuElement=document.querySelector("."+i),this._menuElement.style["border-radius"]="4px",this._menuElement.style.display="none",this._menuElement.style["z-index"]=3e5,this._menuElement.style.background="white",this._menuElement.style.border="1px solid black",this._menuElement.style["box-shadow"]="0 4px 5px 0 gray",this._menuElement.oncontextmenu=(e=>{e.preventDefault()}),this._bindActionLinks(this._items)}get items(){return this._items}_buildActionLinks(e,t,i={id:0}){for(let s=0,r=e.length;s<r;s++){const o=e[s];i.groupIdx=s,i.groupLen=r,this._buildActionLinks2(o,t,i)}}_buildActionLinks2(e,t,i){for(let s=0,r=e.length;s<r;s++){const o=e[s];if(!o.title){console.error("ContextMenu item without title - will not include in ContextMenu");continue}if(!o.doAction&&!o.callback){console.error("ContextMenu item without doAction() or callback() - will not include in ContextMenu");continue}if(o.callback){console.error("ContextMenu item has deprecated 'callback' - rename to 'doAction'");continue}const a="xeokit-context-menu-"+this._id+"-"+i.id++,n=o.title;t.push('<li id="'+a+'" class="xeokit-context-menu-item" style="'+(i.groupIdx===i.groupLen-1||s<r-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+n+"</li>"),o._itemId=a}}_bindActionLinks(e,t={id:0}){const i=this;for(let s=0,r=e.length;s<r;s++){const r=e[s];if(utils.isArray(r))this._bindActionLinks(r,t);else{if(r._itemElement=document.getElementById(r._itemId),!r._itemElement){console.error("ContextMenu item element not found: "+r._itemId);continue}r._itemElement.addEventListener("click",function(){const e=r.doAction||r.callback;return function(t){i._context&&(e(i._context),i.hide(),t.preventDefault())}}())}}}set enabled(e){this._enabled=e,this._enabled||this.hide()}get enabled(){return this._enabled}set context(e){this._context=e}get context(){return this._context}show(e,t){if(!this._context)return void console.error("ContextMenu cannot be shown without a context - set context first");if(!this._enabled||!this._menuElement)return;this._enableItems(),this._menuElement.style.display="block";const i=this._menuElement.offsetHeight,s=this._menuElement.offsetWidth;t+i>window.innerHeight&&(t=window.innerHeight-i),e+s>window.innerWidth&&(e=window.innerWidth-s),this._menuElement.style.left=e+"px",this._menuElement.style.top=t+"px"}_enableItems(){if(this._context)for(let e=0,t=this._items.length;e<t;e++){const t=this._items[e];for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!i._itemElement)continue;const s=i.getEnabled;if(s){s(this._context)?i._itemElement.classList.remove("disabled"):i._itemElement.classList.add("disabled")}}}}hide(){this._menuElement&&(this._menuElement.style.display="none")}destroy(){this._menuElement&&(this._menuElement.parentElement.removeChild(this._menuElement),this._menuElement=null),null!==this._id&&(idMap.removeItem(this._id),this._id=null)}}class SectionToolContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class SectionTool extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._buttonElement=t.buttonElement,this._counterElement=t.counterElement,this._sectionPlanesPlugin=new SectionPlanesPlugin(this.viewer,{}),this._sectionToolContextMenu=new SectionToolContextMenu,this._sectionPlanesPlugin.setOverviewVisible(!1),this.on("enabled",e=>{e?(this._buttonElement.classList.remove("disabled"),this._counterElement&&this._counterElement.classList.remove("disabled")):(this._buttonElement.classList.add("disabled"),this._counterElement&&this._counterElement.classList.add("disabled"))}),this.on("active",e=>{e?(this._buttonElement.classList.add("active"),this._counterElement&&this._counterElement.classList.add("active")):(this._buttonElement.classList.remove("active"),this._counterElement&&this._counterElement.classList.remove("active"))}),this.on("active",e=>{e||this._sectionPlanesPlugin.hideControl()}),this._buttonElement.addEventListener("click",e=>{if(!this.getEnabled())return;const t=this.getActive();this.setActive(!t),e.preventDefault()}),this._buttonElement.oncontextmenu=(e=>{this._sectionToolContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,sectionTool:this},this._sectionToolContextMenu.show(e.pageX,e.pageY),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.clear(),this.setActive(!1)}),this._initSectionMode()}_initSectionMode(){this.viewer.scene.input.on("mouseclicked",e=>{if(!this.getActive()||!this.getEnabled())return;const t=this.viewer.scene.pick({canvasPos:e,pickSurface:!0});if(t){const e=this._sectionPlanesPlugin.createSectionPlane({pos:t.worldPos,dir:math.mulVec3Scalar(t.worldNormal,-1)});this._sectionPlanesPlugin.showControl(e.id),this._updateSectionPlanesCount()}}),this._updateSectionPlanesCount()}_updateSectionPlanesCount(){this._counterElement&&(this._counterElement.innerText=""+this.getNumSections())}getNumSections(){return Object.keys(this._sectionPlanesPlugin.sectionPlanes).length}clear(){this._sectionPlanesPlugin.clear(),this._updateSectionPlanesCount()}destroy(){this._sectionPlanesPlugin.destroy(),this._sectionToolContextMenu.destroy(),super.destroy()}}const webglEnums={funcAdd:"FUNC_ADD",funcSubtract:"FUNC_SUBTRACT",funcReverseSubtract:"FUNC_REVERSE_SUBTRACT",zero:"ZERO",one:"ONE",srcColor:"SRC_COLOR",oneMinusSrcColor:"ONE_MINUS_SRC_COLOR",dstColor:"DST_COLOR",oneMinusDstColor:"ONE_MINUS_DST_COLOR",srcAlpha:"SRC_ALPHA",oneMinusSrcAlpha:"ONE_MINUS_SRC_ALPHA",dstAlpha:"DST_ALPHA",oneMinusDstAlpha:"ONE_MINUS_DST_ALPHA",contantColor:"CONSTANT_COLOR",oneMinusConstantColor:"ONE_MINUS_CONSTANT_COLOR",constantAlpha:"CONSTANT_ALPHA",oneMinusConstantAlpha:"ONE_MINUS_CONSTANT_ALPHA",srcAlphaSaturate:"SRC_ALPHA_SATURATE",front:"FRONT",back:"BACK",frontAndBack:"FRONT_AND_BACK",never:"NEVER",less:"LESS",equal:"EQUAL",lequal:"LEQUAL",greater:"GREATER",notequal:"NOTEQUAL",gequal:"GEQUAL",always:"ALWAYS",cw:"CW",ccw:"CCW",linear:"LINEAR",nearest:"NEAREST",linearMipmapNearest:"LINEAR_MIPMAP_NEAREST",nearestMipmapNearest:"NEAREST_MIPMAP_NEAREST",nearestMipmapLinear:"NEAREST_MIPMAP_LINEAR",linearMipmapLinear:"LINEAR_MIPMAP_LINEAR",repeat:"REPEAT",clampToEdge:"CLAMP_TO_EDGE",mirroredRepeat:"MIRRORED_REPEAT",alpha:"ALPHA",rgb:"RGB",rgba:"RGBA",luminance:"LUMINANCE",luminanceAlpha:"LUMINANCE_ALPHA",textureBinding2D:"TEXTURE_BINDING_2D",textureBindingCubeMap:"TEXTURE_BINDING_CUBE_MAP",compareRToTexture:"COMPARE_R_TO_TEXTURE",unsignedByte:"UNSIGNED_BYTE"};function getGLEnum(e,t,i){if(void 0===t)return i;const s=webglEnums[t];return void 0===s?i:e[s]}const color$1=new Uint8Array([0,0,0,1]);class Texture2D{constructor(e,t){this.gl=e,this.target=t||e.TEXTURE_2D,this.texture=e.createTexture(),this.setPreloadColor([0,0,0,0]),this.allocated=!0}setPreloadColor(e){e?(color$1[0]=Math.floor(255*e[0]),color$1[1]=Math.floor(255*e[1]),color$1[2]=Math.floor(255*e[2]),color$1[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(color$1[0]=0,color$1[1]=0,color$1[2]=0,color$1[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,t.NEAREST),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,color$1)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,color$1);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t){const i=this.gl;if(i.bindTexture(this.target,this.texture),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,t.flipY),this.target===i.TEXTURE_CUBE_MAP){if(utils.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,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,t[e])}}else i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e);i.bindTexture(this.target,null)}setProps(e){const t=this.gl;if(t.bindTexture(this.target,this.texture),e.minFilter){const i=getGLEnum(t,e.minFilter);i&&(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(e.magFilter){const i=getGLEnum(t,e.magFilter);i&&t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,i)}if(e.wrapS){const i=getGLEnum(t,e.wrapS);i&&t.texParameteri(this.target,t.TEXTURE_WRAP_S,i)}if(e.wrapT){const i=getGLEnum(t,e.wrapT);i&&t.texParameteri(this.target,t.TEXTURE_WRAP_T,i)}t.bindTexture(this.target,null)}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 ensureImageSizePowerOfTwo(e){if(!isPowerOfTwo(e.width)||!isPowerOfTwo(e.height)){const t=document.createElement("canvas");t.width=nextHighestPowerOfTwo(e.width),t.height=nextHighestPowerOfTwo(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function isPowerOfTwo(e){return 0==(e&e-1)}function nextHighestPowerOfTwo(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Texture extends Component{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new RenderState({texture:new Texture2D(this.scene.canvas.gl),matrix:math.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=math.vec2([0,0]),this._scale=math.vec2([1,1]),this._rotate=math.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),stats.memory.textures++}_checkMinFilter(e){return"linear"!==(e=e||"linearMipmapLinear")&&"linearMipmapNearest"!==e&&"linearMipmapLinear"!==e&&"nearestMipmapLinear"!==e&&"nearestMipmapNearest"!==e&&(this.error("Unsupported value for 'minFilter': '"+e+"' - supported values are 'linear', 'linearMipmapNearest', 'nearestMipmapNearest', 'nearestMipmapLinear' and 'linearMipmapLinear'. Defaulting to 'linearMipmapLinear'."),e="linearMipmapLinear"),e}_checkMagFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkWrapS(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapS': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkWrapT(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapT': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkFlipY(e){return!!e}_checkEncoding(e){return"linear"!==(e=e||"linear")&&"sRGB"!==e&&"gamma"!==e&&(this.error("Unsupported value for 'encoding': '"+e+"' - supported values are 'linear', 'sRGB', 'gamma'. Defaulting to 'linear'."),e="linear"),e}_webglContextRestored(){this._state.texture=new Texture2D(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=math.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=math.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?math.mulMat4(t,i):i),0!==this._rotate&&(i=math.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?math.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=ensureImageSizePowerOfTwo(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._state.texture.setProps(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=ensureImageSizePowerOfTwo(i),t._state.texture.setImage(i,t._state),t._state.texture.setProps(t._state),t.scene.loading--,t.scene.canvas.spinner.processes--,t.glRedraw()},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(),stats.memory.textures--}}function CubeTextureCanvas(e,t={}){const i="lightgrey",s=t.hoverColor||"rgba(0,0,0,0.4)";var r=500+500/3,o=r/24;const a=[{boundary:[6,6,6,6],color:t.frontColor||t.color||"#55FF55"},{boundary:[18,6,6,6],color:t.backColor||t.color||"#55FF55"},{boundary:[12,6,6,6],color:t.leftColor||t.color||"#FF5555"},{boundary:[0,6,6,6],color:t.rightColor||t.color||"#FF5555"},{boundary:[6,0,6,6],color:t.topColor||t.color||"#7777FF"},{boundary:[6,12,6,6],color:t.bottomColor||t.color||"#7777FF"}],n=[{label:"front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,0,1],up:[0,-1,0]},{boundaries:[[7,5,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,0,-1],up:[1,0,1]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,-1],up:[0,-1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,0,-1],up:[-1,0,1]},{boundaries:[[7,11,4,2]],dir:[0,1,1],up:[0,-1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,0,1],up:[-1,0,1]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,0,1],up:[1,0,1]},{boundaries:[[5,7,2,4]],dir:[1,1,0],up:[0,0,1]},{boundaries:[[11,7,2,4]],dir:[-1,1,0],up:[0,0,1]},{boundaries:[[17,7,2,4]],dir:[-1,-1,0],up:[0,0,1]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,-1,0],up:[0,0,1]},{boundaries:[[5,11,2,2]],dir:[1,1,1],up:[-1,-1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,-1,1],up:[-1,1,1]},{boundaries:[[5,5,2,2]],dir:[1,1,-1],up:[1,1,1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,-1,1],up:[1,1,1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,-1],up:[-1,-1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,1],up:[1,-1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,-1],up:[1,-1,1]},{boundaries:[[11,5,2,2]],dir:[-1,1,-1],up:[-1,1,1]}],l=(t.frontColor||t.color,t.backColor||t.color,t.leftColor||t.color,t.rightColor||t.color,t.topColor||t.color,t.bottomColor||t.color,[{label:"front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-1,-1],up:[0,1,-1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,-1,0],up:[1,1,0]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,-1,0],up:[-1,1,0]},{boundaries:[[7,11,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,1,0],up:[-1,1,0]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,1,1],up:[0,1,-1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,1,0],up:[1,1,0]},{boundaries:[[5,7,2,4]],dir:[1,0,-1],up:[0,1,0]},{boundaries:[[11,7,2,4]],dir:[-1,0,-1],up:[0,1,0]},{boundaries:[[17,7,2,4]],dir:[-1,0,1],up:[0,1,0]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,0,1],up:[0,1,0]},{boundaries:[[5,11,2,2]],dir:[1,1,-1],up:[-1,1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,1,1],up:[-1,1,-1]},{boundaries:[[5,5,2,2]],dir:[1,-1,-1],up:[1,1,-1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,1,1],up:[1,1,-1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,1],up:[-1,1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,-1],up:[1,1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,1],up:[1,1,1]},{boundaries:[[11,5,2,2]],dir:[-1,-1,-1],up:[-1,1,-1]}]);for(let e=0,t=n.length;e<t;e++)math.normalizeVec3(n[e].dir,n[e].dir),math.normalizeVec3(l[e].dir,l[e].dir);var h=l;this._textureCanvas=document.createElement("canvas"),this._textureCanvas.width=r,this._textureCanvas.height=500,this._textureCanvas.style.width=r+"px",this._textureCanvas.style.height="500px",this._textureCanvas.style.padding="0",this._textureCanvas.style.margin="0",this._textureCanvas.style.top="0",this._textureCanvas.style.background=i,this._textureCanvas.style.position="absolute",this._textureCanvas.style.opacity="1.0",this._textureCanvas.style.visibility="hidden",this._textureCanvas.style["z-index"]=2e6,document.getElementsByTagName("body")[0].appendChild(this._textureCanvas);const c=this._textureCanvas.getContext("2d");function d(){for(let e=0,t=a.length;e<t;e++){const t=a[e],i=t.boundary,s=Math.round(i[0]*o),r=Math.round(i[1]*o),n=Math.round(i[2]*o),l=Math.round(i[3]*o);c.fillStyle=t.color,c.fillRect(s,r,n,l)}for(let a=0,l=h.length;a<l;a++){let l,d,p,m;const _=h[a],g=_.boundaries;for(var e=0,t=g.length;e<t;e++){const t=g[e];l=Math.round(t[0]*o),d=Math.round(t[1]*o),p=Math.round(t[2]*o),m=Math.round(t[3]*o),_.highlighted&&(c.fillStyle=_.highlighted?s:_.color||i,c.fillRect(l,d,p,m))}if(_.label){c.fillStyle="black",c.font="60px sans-serif",c.textAlign="center";var r=l+.5*p,n=d+.7*m;c.fillText(u(_.label),r,n,80)}}}var u=function(){const t={yUp:{front:"+Z",back:"-Z",right:"+X",left:"-X",top:"+Y",bottom:"-Y"},en:{front:"FRONT",back:"BACK",right:"RIGHT",left:"LEFT",top:"TOP",bottom:"BOTTOM"}};return function(i){var s;return(s=t[e.language||"en"])&&s[i]||i}}();this.setZUp=function(){h=n,this.clear()},this.setYUp=function(){h=l,this.clear()},this.clear=function(){c.fillStyle=i,c.fillRect(0,0,r,500);for(var e=0,t=h.length;e<t;e++){h[e].highlighted=!1}d()},this.getArea=function(e){const t=e[0]*r,i=500-500*e[1];for(var s=0,a=h.length;s<a;s++){const e=h[s].boundaries;for(var n=0,l=e.length;n<l;n++){const r=e[n];if(t>=r[0]*o&&t<=(r[0]+r[2])*o&&i>=r[1]*o&&i<=(r[1]+r[3])*o)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=h[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,d()},this.getAreaDir=function(e){var t=h[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=h[e];if(!t)throw"Unknown area: "+e;return t.up},this.getImage=function(){return this._textureCanvas},this.destroy=function(){this._textureCanvas&&(this._textureCanvas.parentNode.removeChild(this._textureCanvas),this._textureCanvas=null)},this.clear()}class NavCubePlugin extends Plugin{constructor(e,t={}){super("NavCube",e,t),e.navCube=this;try{this._navCubeScene=new Scene({canvasId:t.canvasId,canvasElement:t.canvasElement,transparent:!0}),this._navCubeCanvas=this._navCubeScene.canvas.canvas,this._navCubeScene.input.keyboardEnabled=!1}catch(e){return void this.error(e)}const i=this._navCubeScene;i.clearLights(),new DirLight(i,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new DirLight(i,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new DirLight(i,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._navCubeCamera=i.camera,this._navCubeCamera.ortho.scale=7,this._navCubeCamera.ortho.near=.1,this._navCubeCamera.ortho.far=2e3,this._zUp=Boolean(e.camera.zUp);var s,r,o,a,n=this;this._synchCamera=(s=math.rotationMat4c(-90*math.DEGTORAD,1,0,0),r=math.vec3(),o=math.vec3(),a=math.vec3(),function(){var t=e.camera.eye,i=e.camera.look,l=e.camera.up;r=math.mulVec3Scalar(math.normalizeVec3(math.subVec3(t,i,r)),5),n._zUp?(math.transformVec3(s,r,o),math.transformVec3(s,l,a),n._navCubeCamera.look=[0,0,0],n._navCubeCamera.eye=math.transformVec3(s,r,o),n._navCubeCamera.up=math.transformPoint3(s,l,a)):(n._navCubeCamera.look=[0,0,0],n._navCubeCamera.eye=r,n._navCubeCamera.up=l)}),this._cubeTextureCanvas=new CubeTextureCanvas(e,t),this._cubeSampler=new Texture(i,{image:this._cubeTextureCanvas.getImage(),flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge"}),this._cubeMesh=new Mesh(i,{geometry:new ReadableGeometry(i,{primitive:"triangles",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],positions:[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],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],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]}),material:new PhongMaterial(i,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:this._cubeSampler,emissiveMap:this._cubeSampler}),visible:!0,edges:!0}),this._shadow=new Mesh(i,{geometry:new ReadableGeometry(i,buildCylinderGeometry({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new PhongMaterial(i,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!0,pickable:!1,backfaces:!1}),this._onCameraMatrix=e.camera.on("matrix",this._synchCamera),this._onCameraWorldAxis=e.camera.on("worldAxis",()=>{e.camera.zUp?(this._zUp=!0,this._cubeTextureCanvas.setZUp(),this._repaint(),this._synchCamera()):e.camera.yUp&&(this._zUp=!1,this._cubeTextureCanvas.setYUp(),this._repaint(),this._synchCamera())}),this._onCameraFOV=e.camera.perspective.on("fov",e=>{this._synchProjection&&(this._navCubeCamera.perspective.fov=e)}),this._onCameraProjection=e.camera.on("projection",e=>{this._synchProjection&&(this._navCubeCamera.projection=e)});var l=-1;function h(e){var t=[0,0];if(e){for(var i=e.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t}var c,d,u=null,p=null,m=!1,_=!1,g=.5;n._navCubeCanvas.addEventListener("mouseenter",n._onMouseEnter=function(e){_=!0}),n._navCubeCanvas.addEventListener("mouseleave",n._onMouseLeave=function(e){_=!1}),n._navCubeCanvas.addEventListener("mousedown",n._onMouseDown=function(e){if(1===e.which){u=e.x,p=e.y,c=e.clientX,d=e.clientY;var t=h(e),s=i.pick({canvasPos:t});m=!!s}}),document.addEventListener("mouseup",n._onMouseUp=function(e){if(1===e.which&&(m=!1,null!==u)){var t=h(e),s=i.pick({canvasPos:t,pickSurface:!0});if(s&&s.uv){var r=n._cubeTextureCanvas.getArea(s.uv);if(r>=0&&(document.body.style.cursor="pointer",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),r>=0)){if(n._cubeTextureCanvas.setAreaHighlighted(r,!0),l=r,n._repaint(),e.x<u-3||e.x>u+3||e.y<p-3||e.y>p+3)return;var o=n._cubeTextureCanvas.getAreaDir(r);if(o){var a=n._cubeTextureCanvas.getAreaUp(r);v(o,a,function(){l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1);var e=i.pick({canvasPos:t,pickSurface:!0});if(e&&e.uv){var s=n._cubeTextureCanvas.getArea(e.uv);void 0!==s&&(document.body.style.cursor="pointer",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),s>=0&&(n._cubeTextureCanvas.setAreaHighlighted(s,!0),l=s,n._repaint()))}})}}}}}),document.addEventListener("mousemove",n._onMouseMove=function(t){if(l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1),1!==t.buttons||m){if(m){var s=t.clientX,r=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=(t-c)*-g,r=(i-d)*-g;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),c=t,d=i}(s,r)}if(_){var o=h(t),a=i.pick({canvasPos:o,pickSurface:!0});if(a){if(a.uv){document.body.style.cursor="pointer";var u=n._cubeTextureCanvas.getArea(a.uv);if(u===l)return;l>=0&&n._cubeTextureCanvas.setAreaHighlighted(l,!1),u>=0&&(n._cubeTextureCanvas.setAreaHighlighted(u,!0),n._repaint(),l=u)}}else document.body.style.cursor="default",l>=0&&(n._cubeTextureCanvas.setAreaHighlighted(l,!1),n._repaint(),l=-1)}}});var f,v=(f=math.vec3(),function(t,i,s){var r=n._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,o=math.getAABB3Diag(r);math.getAABB3Center(r,f);var a=Math.abs(o/Math.tan(27.5));e.cameraControl.pivotPos=f,n._cameraFly?e.cameraFlight.flyTo({look:f,eye:[f[0]-a*t[0],f[1]-a*t[1],f[2]-a*t[2]],up:i||[0,1,0],orthoScale:1.3*o,fitFOV:n._cameraFitFOV,duration:n._cameraFlyDuration},s):e.cameraFlight.jumpTo({look:f,eye:[f[0]-a*t[0],f[1]-a*t[1],f[2]-a*t[2]],up:i||[0,1,0],orthoScale:1.3*o,fitFOV:n._cameraFitFOV},s)});this.setVisible(t.visible),this.setCameraFitFOV(t.cameraFitFOV),this.setCameraFly(t.cameraFly),this.setCameraFlyDuration(t.cameraFlyDuration),this.setFitVisible(t.fitVisible),this.setSynchProjection(t.synchProjection)}send(e,t){switch(e){case"language":this._cubeTextureCanvas.clear(),this._repaint()}}_repaint(){const e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}setVisible(e=!0){this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow.visible=e,this._navCubeCanvas.style.visibility=e?"visible":"hidden")}getVisible(){return!!this._navCubeCanvas&&this._cubeMesh.visible}setFitVisible(e=!1){this._fitVisible=e}getFitVisible(){return this._fitVisible}setCameraFly(e=!0){this._cameraFly=e}getCameraFly(){return this._cameraFly}setCameraFitFOV(e=45){this._cameraFitFOV=e}getCameraFitFOV(){return this._cameraFitFOV}setCameraFlyDuration(e=.5){this._cameraFlyDuration=e}getCameraFlyDuration(){return this._cameraFlyDuration}setSynchProjection(e=!1){this._synchProjection=e}getSynchProjection(){return this._synchProjection}destroy(){this._navCubeCanvas&&(this.viewer.camera.off(this._onCameraMatrix),this.viewer.camera.off(this._onCameraWorldAxis),this.viewer.camera.perspective.off(this._onCameraFOV),this.viewer.camera.off(this._onCameraProjection),this._navCubeCanvas.removeEventListener("mouseenter",this._onMouseEnter),this._navCubeCanvas.removeEventListener("mouseleave",this._onMouseLeave),this._navCubeCanvas.removeEventListener("mousedown",this._onMouseDown),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),this._navCubeCanvas=null,this._cubeTextureCanvas.destroy(),this._cubeTextureCanvas=null,this._onMouseEnter=null,this._onMouseLeave=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null),this._navCubeScene.destroy(),this._navCubeScene=null,this._cubeMesh=null,this._shadow=null,super.destroy()}}class NavCubeMode extends Controller{constructor(e,t){if(super(e,t),!t.navCubeCanvasElement)throw"Missing config: navCubeCanvasElement";const i=t.navCubeCanvasElement;this._navCube=new NavCubePlugin(this.viewer,{canvasElement:i,fitVisible:!0,color:"#CFCFCF"}),this._navCube.setVisible(this._active),this.on("active",e=>{this._navCube.setVisible(e)})}destroy(){this._navCube.destroy(),super.destroy()}}class PerformanceMesh{constructor(e,t,i,s,r=null,o=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=math.AABB3(),this._layer=r,this._portionId=o,this._color=[i[0],i[1],i[2],s],this._colorize=[i[0],i[1],i[2],s],this._colorizing=!1,this.numTriangles=0}_initFlags(e){this._layer.initFlags(this._portionId,e)}_setVisible(e){this._layer.setVisible(this._portionId,e)}_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,!1),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,!1),this._colorizing=!1)}_setOpacity(e){this._color[3]=e,this._colorize[3]=e;this._colorizing?this._layer.setColor(this._portionId,this._colorize,!0):this._layer.setColor(this._portionId,this._color,!0)}_setHighlighted(e){this._layer.setHighlighted(this._portionId,e)}_setXRayed(e){this._layer.setXRayed(this._portionId,e)}_setSelected(e){this._layer.setSelected(this._portionId,e)}_setEdges(e){this._layer.setEdges(this._portionId,e)}_setClippable(e){this._layer.setClippable(this._portionId,e)}_setCollidable(e){this._layer.setCollidable(this._portionId,e)}_setPickable(e){this._layer.setPickable(this._portionId,e)}canPickTriangle(){return!1}drawPickTriangles(e){}pickTriangleSurface(e){}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const RENDER_FLAGS={VISIBLE:1,CULLED:4,PICKABLE:8,CLIPPABLE:16,COLLIDABLE:32,CAST_SHADOW:64,RECEIVE_SHADOW:128,XRAYED:256,HIGHLIGHTED:512,SELECTED:1024,EDGES:2048,BACKFACES:4096},tempFloatRGB=new Float32Array([0,0,0]),tempIntRGB=new Uint16Array([0,0,0]);class PerformanceNode{constructor(e,t,i,s,r,o){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=s,this._numTriangles=0;for(var a=0,n=this.meshes.length;a<n;a++){const e=this.meshes[a];e.parent=this,this._numTriangles+=e.numTriangles}this.id=i,this._flags=r,this._aabb=o,this._isObject&&e.scene._registerObject(this)}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get aabb(){return this._aabb}get numTriangles(){return this._numTriangles}set visible(e){if(!!(this._flags&RENDER_FLAGS.VISIBLE)!==e){this._flags=e?this._flags|RENDER_FLAGS.VISIBLE:this._flags&~RENDER_FLAGS.VISIBLE;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}get visible(){return this._getFlag(RENDER_FLAGS.VISIBLE)}_getFlag(e){return!!(this._flags&e)}set highlighted(e){if(!!(this._flags&RENDER_FLAGS.HIGHLIGHTED)!==e){this._flags=e?this._flags|RENDER_FLAGS.HIGHLIGHTED:this._flags&~RENDER_FLAGS.HIGHLIGHTED;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get highlighted(){return this._getFlag(RENDER_FLAGS.HIGHLIGHTED)}set xrayed(e){if(!!(this._flags&RENDER_FLAGS.XRAYED)!==e){this._flags=e?this._flags|RENDER_FLAGS.XRAYED:this._flags&~RENDER_FLAGS.XRAYED;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(RENDER_FLAGS.XRAYED)}set selected(e){if(!!(this._flags&RENDER_FLAGS.SELECTED)!==e){this._flags=e?this._flags|RENDER_FLAGS.SELECTED:this._flags&~RENDER_FLAGS.SELECTED;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}get selected(){return this._getFlag(RENDER_FLAGS.SELECTED)}set edges(e){if(!!(this._flags&RENDER_FLAGS.EDGES)!==e){this._flags=e?this._flags|RENDER_FLAGS.EDGES:this._flags&~RENDER_FLAGS.EDGES;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get edges(){return this._getFlag(RENDER_FLAGS.EDGES)}set culled(e){}get culled(){return!1}set clippable(e){if(!!(this._flags&RENDER_FLAGS.CLIPPABLE)!==e){this._flags=e?this._flags|RENDER_FLAGS.CLIPPABLE:this._flags&~RENDER_FLAGS.CLIPPABLE;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(RENDER_FLAGS.CLIPPABLE)}set collidable(e){if(!!(this._flags&RENDER_FLAGS.COLLIDABLE)!==e){this._flags=e?this._flags|RENDER_FLAGS.COLLIDABLE:this._flags&~RENDER_FLAGS.COLLIDABLE;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get collidable(){return this._getFlag(RENDER_FLAGS.COLLIDABLE)}set pickable(e){if(!!(this._flags&RENDER_FLAGS.PICKABLE)!==e){this._flags=e?this._flags|RENDER_FLAGS.PICKABLE:this._flags&~RENDER_FLAGS.PICKABLE;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}get pickable(){return this._getFlag(RENDER_FLAGS.PICKABLE)}set colorize(e){if(e){tempIntRGB[0]=Math.floor(255*e[0]),tempIntRGB[1]=Math.floor(255*e[1]),tempIntRGB[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(tempIntRGB)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}this.model.glRedraw()}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return tempFloatRGB[0]=e[0]/255,tempFloatRGB[1]=e[1]/255,tempFloatRGB[2]=e[2]/255,tempFloatRGB}set opacity(e){if(0!==this.meshes.length&&(e<0?e=0:e>1&&(e=1),e=Math.floor(255*e),this.meshes[0]._colorize[3]/255!==e)){for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setOpacity(e);this.model.glRedraw()}}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set castsShadow(e){}get castsShadow(){return!1}set receivesShadow(e){}get receivesShadow(){return!1}get saoEnabled(){return this.model.saoEnabled}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._initFlags(this._flags)}_destroy(){const e=this.model.scene;if(this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this._isObject)){const e=!1;this.scene._objectColorizeUpdated(this,e)}for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._destroy();e._aabbDirty=!0}}const bigIndicesSupported$1=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,SLICING=!0,MAX_VERTS=bigIndicesSupported$1?5e6:65530,MAX_INDICES=3*MAX_VERTS;class BatchingBuffer{constructor(){this.slicing=SLICING,this.maxVerts=MAX_VERTS,this.maxIndices=MAX_INDICES,this.positions=new Float32Array(3*MAX_VERTS),this.colors=new Uint8Array(4*MAX_VERTS),this.quantizedPositions=new Uint16Array(3*MAX_VERTS),this.normals=new Int8Array(3*MAX_VERTS),this.pickColors=new Uint8Array(4*MAX_VERTS),this.flags=new Uint8Array(4*MAX_VERTS),this.flags2=new Uint8Array(4*MAX_VERTS),this.indices=bigIndicesSupported$1?new Uint32Array(MAX_INDICES):new Uint16Array(MAX_INDICES),this.edgeIndices=bigIndicesSupported$1?new Uint32Array(MAX_INDICES):new Uint16Array(MAX_INDICES),this.lenPositions=0,this.lenColors=0,this.lenNormals=0,this.lenPickColors=0,this.lenFlags=0,this.lenIndices=0,this.lenEdgeIndices=0}}const freeBuffers=[];function getBatchingBuffer(){return freeBuffers.length>0?freeBuffers.pop():new BatchingBuffer}function putBatchingBuffer(e){freeBuffers.push(e)}class BatchingLayerScratchMemory{constructor(){this._uint8Arrays={}}_clear(){this._uint8Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}}const batchingLayerScratchMemory=new BatchingLayerScratchMemory;function getBatchingLayerScratchMemory(e){return e.once("destroyed",()=>{batchingLayerScratchMemory._clear()}),batchingLayerScratchMemory}const RENDER_PASSES={NORMAL_OPAQUE:0,NORMAL_TRANSPARENT:1,NORMAL_EDGES:2,HIGHLIGHTED:3,HIGHLIGHTED_EDGES:4,XRAYED:5,XRAYED_EDGES:6,SELECTED:7,SELECTED_EDGES:8},BatchingDrawShaderSource=function(e,t){this.vertex=buildVertex$5(e),this.fragment=buildFragment$5(e,t)};function buildVertex$5(e){const t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r,o,a;const n=[];for(n.push("// Batched geometry drawing vertex shader"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),n.push("attribute vec3 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),s&&n.push("attribute vec4 flags2;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),n.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r<o;r++)"ambient"!==(a=i.lights[r]).type&&(n.push("uniform vec4 lightColor"+r+";"),"dir"===a.type&&n.push("uniform vec3 lightDir"+r+";"),"point"===a.type&&n.push("uniform vec3 lightPos"+r+";"),"spot"===a.type&&(n.push("uniform vec3 lightPos"+r+";"),n.push("uniform vec3 lightDir"+r+";")));for(n.push("vec3 octDecode(vec2 oct) {"),n.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push("    if (v.z < 0.0) {"),n.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);"),n.push("    }"),n.push("    return normalize(v);"),n.push("}"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vColor;"),n.push("void main(void) {"),n.push("bool visible      = (float(flags.x) > 0.0);"),n.push("bool xrayed       = (float(flags.y) > 0.0);"),n.push("bool highlighted  = (float(flags.z) > 0.0);"),n.push("bool selected     = (float(flags.w) > 0.0);"),n.push("bool transparent  = ((float(color.a) / 255.0) < 1.0);"),n.push(`if (\n    !visible ||  \n    (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n    (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n    (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),n.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = (positionsDecodeMatrix * vec4(position, 1.0)); "),n.push("vec4 viewPosition  = viewMatrix * worldPosition; "),n.push("vec4 worldNormal =  vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),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;"),r=0,o=i.lights.length;r<o;r++)if("ambient"!==(a=i.lights[r]).type){if("dir"===a.type)"view"===a.space?n.push("viewLightDir = normalize(lightDir"+r+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);");else if("point"===a.type)"view"===a.space?n.push("viewLightDir = normalize(lightPos"+r+" - viewPosition.xyz);"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightPos"+r+", 0.0)).xyz);");else{if("spot"!==a.type)continue;"view"===a.space?n.push("viewLightDir = normalize(lightDir"+r+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+r+".rgb * lightColor"+r+".a);")}return n.push("vColor =  vec4(reflectedColor * ((lightAmbient.rgb * lightAmbient.a) + vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0)), float(color.a) / 255.0);"),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2;")),n.push("gl_Position = projMatrix * viewPosition;"),n.push("}"),n.push("}"),n}function buildFragment$5(e,t){const i=e._sectionPlanesState;let s,r;const o=i.sectionPlanes.length>0,a=[];if(a.push("// Batched geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4      uSAOParams;"),a.push("const float       packUpscale = 256. / 255.;"),a.push("const float       unpackDownScale = 255. / 256.;"),a.push("const vec3        packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),a.push("const vec4        unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push("    return dot( v, unPackFactors );"),a.push("}")),o)for(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),s=0,r=i.sectionPlanes.length;s<r;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("varying vec4 vColor;"),a.push("void main(void) {"),o){for(a.push("  bool clippable = (float(vFlags2.x) > 0.0);"),a.push("  if (clippable) {"),a.push("  float dist = 0.0;"),s=0,r=i.sectionPlanes.length;s<r;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push("   dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("  if (dist > 0.0) { discard; }"),a.push("}")}return t?(a.push("   float viewportWidth     = uSAOParams[0];"),a.push("   float viewportHeight    = uSAOParams[1];"),a.push("   float blendCutoff       = uSAOParams[2];"),a.push("   float blendFactor       = uSAOParams[3];"),a.push("   vec2 uv                 = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push("   float ambient           = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push("   gl_FragColor            = vec4(vColor.rgb * ambient, vColor.a);")):a.push("   gl_FragColor            = vColor;"),a.push("}"),a}const tempVec4$1=math.vec4();class BatchingDrawRenderer{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._shaderSource=new BatchingDrawShaderSource(this._scene,this._withSAO),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=t.model,o=s.canvas.gl,a=t._state;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),o.uniformMatrix4fv(this._uViewMatrix,!1,r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),o.uniform1i(this._uRenderPass,i),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),o.drawElements(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState,s=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uViewNormalMatrix=r.getLocation("viewNormalMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const o=i.lights;let a;for(let e=0,t=o.length;e<t;e++)switch((a=o[e]).type){case"ambient":this._uLightAmbient[e]=r.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=r.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=r.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=r.getLocation("lightColor"+e),this._uLightPos[e]=r.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=r.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=r.getLocation("lightColor"+e),this._uLightPos[e]=r.getLocation("lightPos"+e),this._uLightDir[e]=r.getLocation("lightDir"+e),this._uLightAttenuation[e]=r.getLocation("lightAttenuation"+e)}this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+e),pos:r.getLocation("sectionPlanePos"+e),dir:r.getLocation("sectionPlaneDir"+e)});this._aPosition=r.getAttribute("position"),this._aNormal=r.getAttribute("normal"),this._aColor=r.getAttribute("color"),this._aFlags=r.getAttribute("flags"),this._aFlags2=r.getAttribute("flags2"),this._withSAO&&(this._uSAOEnabled=r.getLocation("uSAOEnabled"),this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState,o=t._sectionPlanesState,a=r.lights;let n;s.bind();const l=t.camera;i.uniformMatrix4fv(this._uProjMatrix,!1,l._project._state.matrix);for(let e=0,t=a.length;e<t;e++)n=a[e],this._uLightAmbient[e]?i.uniform4f(this._uLightAmbient[e],n.color[0],n.color[1],n.color[2],n.intensity):(this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],n.color[0],n.color[1],n.color[2],n.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],n.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],n.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],n.dir));if(o.sectionPlanes.length>0){const e=t._sectionPlanesState.sectionPlanes;let s,r,o,a,n;for(var h=0,c=this._uSectionPlanes.length;h<c;h++)r=(s=this._uSectionPlanes[h]).active,o=e[h],r&&i.uniform1i(r,o.active),(a=s.pos)&&i.uniform3fv(s.pos,o.pos),(n=s.dir)&&i.uniform3fv(s.dir,o.dir)}if(this._withSAO){const s=t.sao;if(s.possible){const t=i.drawingBufferWidth,r=i.drawingBufferHeight;tempVec4$1[0]=t,tempVec4$1[1]=r,tempVec4$1[2]=s.blendCutoff,tempVec4$1[3]=s.blendFactor,i.uniform4fv(this._uSAOParams,tempVec4$1),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const BatchingFillShaderSource=function(e){this.vertex=buildVertex$6(e),this.fragment=buildFragment$6(e)};function buildVertex$6(e){const t=e._sectionPlanesState,i=(e._lightsState,t.sectionPlanes.length>0),s=[];return s.push("// Batched fill 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"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec4 color;"),i&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("bool visible      = (float(flags.x) > 0.0);"),s.push("bool xrayed       = (float(flags.y) > 0.0);"),s.push("bool highlighted  = (float(flags.z) > 0.0);"),s.push("bool selected     = (float(flags.w) > 0.0);"),s.push("bool clippable    = (float(flags2.x) > 0.0);"),s.push("bool transparent  = (color.a < 1.0);"),s.push(`if (\n    !visible || \n    (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n    (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n    (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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("vec4 viewPosition  = viewMatrix * worldPosition; "),i&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("gl_Position = projMatrix * viewPosition;"),s.push("}"),s.push("}"),s}function buildFragment$6(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Batched fill 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;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("void main(void) {"),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;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("gl_FragColor = color;"),o.push("}"),o}class BatchingFillRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingFillShaderSource(this._scene),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.canvas.gl,a=t._state;if(this._program||(this._allocate(),!this.errors)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),o.uniformMatrix4fv(this._uViewMatrix,!1,s.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,s.viewNormalMatrix),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,s.worldMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),i===RENDER_PASSES.XRAYED){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;o.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===RENDER_PASSES.HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;o.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===RENDER_PASSES.SELECTED){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;o.uniform4f(this._uColor,t[0],t[1],t[2],i)}else o.uniform4fv(this._uColor,defaultColor);o.drawElements(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;i.bind();const r=e.camera;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,o,a,n;for(let e=0,l=this._uSectionPlanes.length;e<l;e++)r=(s=this._uSectionPlanes[e]).active,o=i[e],r&&t.uniform1i(r,o.active),(a=s.pos)&&t.uniform3fv(s.pos,o.pos),(n=s.dir)&&t.uniform3fv(s.dir,o.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const BatchingEdgesShaderSource=function(e){this.vertex=buildVertex$7(e),this.fragment=buildFragment$7(e)};function buildVertex$7(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return 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("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("uniform vec4 color;"),i.push("void main(void) {"),i.push("bool visible      = (float(flags.x) > 0.0);"),i.push("bool xrayed       = (float(flags.y) > 0.0);"),i.push("bool highlighted  = (float(flags.z) > 0.0);"),i.push("bool selected     = (float(flags.w) > 0.0);"),i.push("bool edges        = (float(flags2.y) > 0.0);"),i.push("bool transparent  = (color.a < 1.0);"),i.push(`if (\n    !visible ||\n    (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (!edges || transparent || xrayed)) ||\n    (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} &&  (!edges || !transparent || xrayed || highlighted || selected)) ||\n    (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) ||\n    (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n    (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("  vWorldPosition = worldPosition;"),i.push("  vFlags2 = flags2;")),i.push("  gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$7(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Batched geometry 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;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("void main(void) {"),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;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("gl_FragColor = color;"),o.push("}"),o}class BatchingEdgesRenderer{constructor(e){this._scene=e,this._shaderSource=new BatchingEdgesShaderSource(this._scene),this._allocate(),this._hash=this._getHash()}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.canvas.gl,a=t._state;if(!this._program&&(this._allocate(),this.errors))return;let n;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const l=(n=i===RENDER_PASSES.XRAYED?r.xrayMaterial._state:i===RENDER_PASSES.HIGHLIGHTED?r.highlightMaterial._state:i===RENDER_PASSES.SELECTED?r.selectedMaterial._state:r.edgeMaterial._state).edgeColor,h=n.edgeAlpha;o.uniform4f(this._uColor,l[0],l[1],l[2],h),e.lineWidth!==n.edgeWidth&&(o.lineWidth(n.edgeWidth),e.lineWidth=n.edgeWidth),o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),o.uniformMatrix4fv(this._uViewMatrix,!1,s.viewMatrix),o.uniform1i(this._uRenderPass,i),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.edgeIndicesBuf.bind(),o.drawElements(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uColor=s.getLocation("color"),this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;i.bind();const r=e.camera;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,n,l,h;for(var o=0,a=this._uSectionPlanes.length;o<a;o++)r=(s=this._uSectionPlanes[o]).active,n=i[o],r&&t.uniform1i(r,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class BatchingPickMeshShaderSource{constructor(e){this.vertex=buildVertex$8(e),this.fragment=buildFragment$8(e)}}function buildVertex$8(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry picking vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push("  bool visible   = (float(flags.x) > 0.0);"),i.push("  bool pickable  = (float(flags2.z) > 0.0);"),i.push("  if ((!pickInvisible && !visible) || !pickable) {"),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("      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("      vFlags2 = flags2;")),i.push("      gl_Position = projMatrix * viewPosition;"),i.push("  }"),i.push("}"),i}function buildFragment$8(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return s.push("   gl_FragColor = vPickColor; "),s.push("}"),s}class BatchingPickMeshRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickMeshShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),s.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(r.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(r.flags2Buf),this._aPickColor&&this._aPickColor.bindArrayBuffer(r.pickColorsBuf),r.indicesBuf.bind(),s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aPickColor=s.getAttribute("pickColor"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._sectionPlanesState,o=t.camera;if(s.bind(),i.uniform1i(this._uPickInvisible,e.pickInvisible),i.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix||o.project._state.matrix),r.sectionPlanes.length>0){const e=t._sectionPlanesState.sectionPlanes;let s,r,o,l,h;for(var a=0,n=this._uSectionPlanes.length;a<n;a++)r=(s=this._uSectionPlanes[a]).active,o=e[a],r&&i.uniform1i(r,o.active),(l=s.pos)&&i.uniform3fv(s.pos,o.pos),(h=s.dir)&&i.uniform3fv(s.dir,o.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class BatchingPickDepthShaderSource{constructor(e){this.vertex=buildVertex$9(e),this.fragment=buildFragment$9(e)}}function buildVertex$9(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("  bool visible   = (float(flags.x) > 0.0);"),i.push("  bool pickable  = (float(flags2.z) > 0.0);"),i.push("  if ((!pickInvisible && !visible) || !pickable) {"),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("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("      vViewPosition = viewPosition;"),i.push("      gl_Position = projMatrix * viewPosition;"),i.push("  }"),i.push("}"),i}function buildFragment$9(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),s.push("uniform float zNear;"),s.push("uniform float zFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying 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("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return s.push("    float zNormalizedDepth = abs((zNear + vViewPosition.z) / (zFar - zNear));"),s.push("    gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}class BatchingPickDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=s.camera.project._state;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.uniform1f(this._uZNear,a.near),r.uniform1f(this._uZFar,a.far),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),o.indicesBuf.bind(),r.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._uZNear=s.getLocation("zNear"),this._uZFar=s.getLocation("zFar")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;e.camera;if(i.bind(),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,a,n,l,h;for(var r=0,o=this._uSectionPlanes.length;r<o;r++)a=(s=this._uSectionPlanes[r]).active,n=i[r],a&&t.uniform1i(a,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class BatchingPickNormalsShaderSource{constructor(e){this.vertex=buildVertex$a(e),this.fragment=buildFragment$a(e)}}function buildVertex$a(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry normals vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("  bool visible   = (float(flags.x) > 0.0);"),i.push("  bool pickable  = (float(flags2.z) > 0.0);"),i.push("  if ((!pickInvisible && !visible) || !pickable) {"),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("      vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("      vec3 worldNormal =  octDecode(normal.xy); "),i.push("      vWorldNormal = worldNormal;"),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("      gl_Position = projMatrix * viewPosition;"),i.push("  }"),i.push("}"),i}function buildFragment$a(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec3 vWorldNormal;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return s.push("    gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}class BatchingPickNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingPickNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),s.uniform1i(this._uPickInvisible,e.pickInvisible),s.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(r.normalsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(r.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(r.flags2Buf),r.indicesBuf.bind(),s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0)}_allocate(){var e=this._scene;const t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aNormal=s.getAttribute("normal"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;e.camera;if(i.bind(),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,a,n,l,h;for(var r=0,o=this._uSectionPlanes.length;r<o;r++)a=(s=this._uSectionPlanes[r]).active,n=i[r],a&&t.uniform1i(a,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class BatchingOcclusionShaderSource{constructor(e){this.vertex=buildVertex$b(e),this.fragment=buildFragment$b(e)}}function buildVertex$b(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched occlusion vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),t&&i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("  bool visible   = (float(flags.x) > 0.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("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("      gl_Position = projMatrix * viewPosition;"),i.push("  }"),i.push("}"),i}function buildFragment$b(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched 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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return s.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}class BatchingOcclusionRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingOcclusionShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=s.camera;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),r.uniformMatrix4fv(this._uViewMatrix,!1,i.viewMatrix),r.uniformMatrix4fv(this._uProjMatrix,!1,a._project._state.matrix),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aColor&&this._aColor.bindArrayBuffer(o.colorsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(o.flags2Buf),o.indicesBuf.bind(),r.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;if(i.bind(),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,a,n,l,h;for(var r=0,o=this._uSectionPlanes.length;r<o;r++)a=(s=this._uSectionPlanes[r]).active,n=i[r],a&&t.uniform1i(a,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class BatchingDepthShaderSource{constructor(e){this.vertex=buildVertex$c(e),this.fragment=buildFragment$c(e)}}function buildVertex$c(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),t&&i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("  bool visible        = (float(flags.x) > 0.0);"),i.push("  bool xrayed         = (float(flags.y) > 0.0);"),i.push("  bool transparent    = ((float(color.a) / 255.0) < 1.0);"),i.push("  if (!visible || transparent || xrayed) {"),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("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("      vViewPosition = viewPosition;"),i.push("      gl_Position = projMatrix * viewPosition;"),i.push("  }"),i.push("}"),i}function buildFragment$c(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vViewPosition;"),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("const float   shiftRight8 = 1. / 256.;"),s.push("vec4 packDepthToRGBA( const in float v ) {"),s.push("    vec4 r = vec4( fract( v * packFactors ), v );"),s.push("    r.yzw -= r.xyz * shiftRight8;"),s.push("    return r * packUpScale;"),s.push("}"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return s.push("    gl_FragColor = packDepthToRGBA( gl_FragCoord.z); "),s.push("}"),s}class BatchingDepthRenderer{constructor(e){this._scene=e,this._shaderSource=new BatchingDepthShaderSource(this._scene),this._allocate(this._scene),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),s.uniformMatrix4fv(this._uViewMatrix,!1,i.viewMatrix),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aColor&&this._aColor.bindArrayBuffer(r.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(r.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(r.flags2Buf),r.indicesBuf.bind(),s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;i.bind();const r=e.camera;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,o,a,n;for(let e=0,l=this._uSectionPlanes.length;e<l;e++)r=(s=this._uSectionPlanes[e]).active,o=i[e],r&&t.uniform1i(r,o.active),(a=s.pos)&&t.uniform3fv(s.pos,o.pos),(n=s.dir)&&t.uniform3fv(s.dir,o.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,stats.memory.programs--}}class BatchingNormalsShaderSource{constructor(e){this.vertex=buildVertex$d(e),this.fragment=buildFragment$d(e)}}function buildVertex$d(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry normals vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),t&&i.push("attribute vec4 flags2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("  bool visible        = (float(flags.x) > 0.0);"),i.push("  bool xrayed         = (float(flags.y) > 0.0);"),i.push("  bool transparent    = ((float(color.a) / 255.0) < 1.0);"),i.push("  if (!visible || transparent || xrayed) {"),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("      vec4 viewPosition   = viewMatrix * worldPosition; "),i.push("      vec4 worldNormal    = 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("      gl_Position = projMatrix * viewPosition;"),i.push("  }"),i.push("}"),i}function buildFragment$d(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push("    return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return s.push("    gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}class BatchingNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new BatchingNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),s.uniformMatrix4fv(this._uViewMatrix,!1,i.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aNormal.bindArrayBuffer(r.normalsBuf),this._aColor.bindArrayBuffer(r.colorsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(r.flags2Buf),r.indicesBuf.bind(),s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2&&(this._aFlags2=s.getAttribute("flags2"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;i.bind();const r=e.camera;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,o,a,n;for(let e=0,l=this._uSectionPlanes.length;e<l;e++)r=(s=this._uSectionPlanes[e]).active,o=i[e],r&&t.uniform1i(r,o.active),(a=s.pos)&&t.uniform3fv(s.pos,o.pos),(n=s.dir)&&t.uniform3fv(s.dir,o.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class BatchingRenderers{constructor(e){this._scene=e}_compile(){this.drawRenderer&&!this.drawRenderer.getValid()&&(this.drawRenderer.destroy(),this.drawRenderer=null),this.drawRendererWithSAO&&!this.drawRendererWithSAO.getValid()&&(this.drawRendererWithSAO.destroy(),this.drawRendererWithSAO=null),this.depthRenderer&&!this.depthRenderer.getValid()&&(this.depthRenderer.destroy(),this.depthRenderer=null),this.normalsRenderer&&!this.normalsRenderer.getValid()&&(this.normalsRenderer.destroy(),this.normalsRenderer=null),this.fillRenderer&&!this.fillRenderer.getValid()&&(this.fillRenderer.destroy(),this.fillRenderer=null),this.edgesRenderer&&!this.edgesRenderer.getValid()&&(this.edgesRenderer.destroy(),this.edgesRenderer=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.occlusionRenderer&&!1===this.occlusionRenderer.getValid()&&(this.occlusionRenderer.destroy(),this.occlusionRenderer=null),this._createRenderers()}_createRenderers(){if(this.drawRenderer||(this.drawRenderer=new BatchingDrawRenderer(this._scene)),!this.drawRendererWithSAO){const e=!0;this.drawRendererWithSAO=new BatchingDrawRenderer(this._scene,e)}this.fillRenderer||(this.fillRenderer=new BatchingFillRenderer(this._scene)),this.edgesRenderer||(this.edgesRenderer=new BatchingEdgesRenderer(this._scene)),this.pickMeshRenderer||(this.pickMeshRenderer=new BatchingPickMeshRenderer(this._scene)),this.pickDepthRenderer||(this.pickDepthRenderer=new BatchingPickDepthRenderer(this._scene)),this.pickNormalsRenderer||(this.pickNormalsRenderer=new BatchingPickNormalsRenderer(this._scene)),this.occlusionRenderer||(this.occlusionRenderer=new BatchingOcclusionRenderer(this._scene)),this.depthRenderer||(this.depthRenderer=new BatchingDepthRenderer(this._scene)),this.normalsRenderer||(this.normalsRenderer=new BatchingNormalsRenderer(this._scene))}_destroy(){this.drawRenderer.destroy(),this.drawRendererWithSAO.destroy(),this.depthRenderer.destroy(),this.normalsRenderer.destroy(),this.fillRenderer.destroy(),this.edgesRenderer.destroy(),this.pickMeshRenderer.destroy(),this.pickDepthRenderer.destroy(),this.pickNormalsRenderer.destroy(),this.occlusionRenderer.destroy()}}const sceneBatchingRenderers={};function getBatchingRenderers(e){const t=e.id;let i=sceneBatchingRenderers[t];return i||(i=new BatchingRenderers(e),sceneBatchingRenderers[t]=i,i._compile(),e.on("compile",()=>{i._compile()}),e.on("destroyed",()=>{delete sceneBatchingRenderers[t],i._destroy()})),i}const tempMat4=math.mat4(),tempMat4b=math.mat4(),tempVec3a$1=math.vec4([0,0,0,1]),tempVec3b$1=math.vec4([0,0,0,1]),tempVec3c$1=math.vec4([0,0,0,1]),tempOBB3=math.OBB3();class BatchingLayer{constructor(e,t){this._batchingRenderers=getBatchingRenderers(e.scene),this.model=e,this._buffer=t.buffer,this._scratchMemory=t.scratchMemory;var i,s=t.primitive||"triangles";const r=e.scene.canvas.gl;switch(s){case"points":i=r.POINTS;break;case"lines":i=r.LINES;break;case"line-loop":i=r.LINE_LOOP;break;case"line-strip":i=r.LINE_STRIP;break;case"triangles":i=r.TRIANGLES;break;case"triangle-strip":i=r.TRIANGLE_STRIP;break;case"triangle-fan":i=r.TRIANGLE_FAN;break;default:e.error(`Unsupported value for 'primitive': '${s}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),i=r.TRIANGLES,s="triangles"}this._state=new RenderState({primitiveName:s,primitive:i,positionsBuf:null,normalsBuf:null,colorsbuf:null,flagsBuf:null,flags2Buf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:math.mat4()}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._modelAABB=math.collapseAABB3(),this._portions=[],this._finalized=!1,this._positionsDecodeMatrix=t.positionsDecodeMatrix,this._preCompressed=!!this._positionsDecodeMatrix}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.lenPositions+e<3*this._buffer.maxVerts&&this._buffer.lenIndices+t<this._buffer.maxIndices}createPortion(e,t,i,s,r,o,a,n,l,h,c){if(this._finalized)throw"Already finalized";const d=this._buffer,u=d.lenPositions/3,p=e.length/3,m=e.length;if(this._preCompressed){d.positions.set(e,d.lenPositions),d.lenPositions+=m;const t=geometryCompressionUtils.getPositionsBounds(e),i=geometryCompressionUtils.decompressPosition(t.min,this._positionsDecodeMatrix,[]),s=geometryCompressionUtils.decompressPosition(t.max,this._positionsDecodeMatrix,[]);h[0]=i[0],h[1]=i[1],h[2]=i[2],h[3]=s[0],h[4]=s[1],h[5]=s[2],l&&(math.AABB3ToOBB3(h,tempOBB3),math.transformOBB3(l,tempOBB3),math.OBB3ToAABB3(tempOBB3,h))}else{if(d.positions.set(e,d.lenPositions),n)for(let e=d.lenPositions,t=d.lenPositions+m;e<t;e+=3)tempVec3a$1[0]=d.positions[e+0],tempVec3a$1[1]=d.positions[e+1],tempVec3a$1[2]=d.positions[e+2],math.transformPoint4(n,tempVec3a$1,tempVec3b$1),d.positions[e+0]=tempVec3b$1[0],d.positions[e+1]=tempVec3b$1[1],d.positions[e+2]=tempVec3b$1[2],math.expandAABB3Point3(this._modelAABB,tempVec3b$1),l?(math.transformPoint4(l,tempVec3b$1,tempVec3c$1),math.expandAABB3Point3(h,tempVec3c$1)):math.expandAABB3Point3(h,tempVec3b$1);else for(let e=d.lenPositions,t=d.lenPositions+m;e<t;e+=3)tempVec3a$1[0]=d.positions[e+0],tempVec3a$1[1]=d.positions[e+1],tempVec3a$1[2]=d.positions[e+2],math.expandAABB3Point3(this._modelAABB,tempVec3a$1),l?(math.transformPoint4(l,tempVec3a$1,tempVec3b$1),math.expandAABB3Point3(h,tempVec3b$1)):math.expandAABB3Point3(h,tempVec3a$1);d.lenPositions+=m}if(t)if(this._preCompressed)d.normals.set(t,d.lenNormals),d.lenNormals+=t.length;else{var _=tempMat4;n?math.inverseMat4(math.transposeMat4(n,tempMat4b),_):math.identityMat4(_,_),d.lenNormals=transformAndOctEncodeNormals(_,t,t.length,d.normals,d.lenNormals)}if(void 0!==r){const e=4*p,t=r&RENDER_FLAGS.VISIBLE?255:0,i=r&RENDER_FLAGS.XRAYED?255:0,s=r&RENDER_FLAGS.HIGHLIGHTED?255:0,o=r&RENDER_FLAGS.SELECTED?255:0,a=r&RENDER_FLAGS.CLIPPABLE?255:0,n=r&RENDER_FLAGS.EDGES?255:0,l=r&RENDER_FLAGS.PICKABLE?255:0;for(var g=d.lenFlags,f=d.lenFlags+e;g<f;g+=4)d.flags[g+0]=t,d.flags[g+1]=i,d.flags[g+2]=s,d.flags[g+3]=o,d.flags2[g+0]=a,d.flags2[g+1]=n,d.flags2[g+2]=l;d.lenFlags+=e,t&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),i&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),s&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),o&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),n&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),l&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++)}if(o){const e=4*p,t=o[0],i=o[1],s=o[2],r=a;for(g=d.lenColors,f=d.lenColors+e;g<f;g+=4)d.colors[g+0]=t,d.colors[g+1]=i,d.colors[g+2]=s,d.colors[g+3]=a;d.lenColors+=e,r<255&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++)}if(i){for(g=0,f=i.length;g<f;g++)d.indices[d.lenIndices+g]=i[g]+u;d.lenIndices+=i.length}if(s){for(g=0,f=s.length;g<f;g++)d.edgeIndices[d.lenEdgeIndices+g]=s[g]+u;d.lenEdgeIndices+=s.length}{const e=4*p;for(g=d.lenPickColors,f=d.lenPickColors+e;g<f;g+=4)d.pickColors[g+0]=c[0],d.pickColors[g+1]=c[1],d.pickColors[g+2]=c[2],d.pickColors[g+3]=c[3];d.lenPickColors+=e}var v=this._portions.length/2;return this._portions.push(u),this._portions.push(p),this._numPortions++,this.model.numPortions++,v}finalize(){if(this._finalized)return void this.error("Already finalized");const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(this._preCompressed?(e.positionsDecodeMatrix=this._positionsDecodeMatrix,e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,i.positions.slice(0,i.lenPositions),i.lenPositions,3,t.STATIC_DRAW)):(quantizePositions(i.positions,i.lenPositions,this._modelAABB,i.quantizedPositions,e.positionsDecodeMatrix),i.lenPositions>0&&(e.positionsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,i.quantizedPositions.slice(0,i.lenPositions),i.lenPositions,3,t.STATIC_DRAW))),i.lenNormals>0){let s=!0;e.normalsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,i.normals.slice(0,i.lenNormals),i.lenNormals,3,t.STATIC_DRAW,s)}if(i.lenColors>0){let s=!1;e.colorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,i.colors.slice(0,i.lenColors),i.lenColors,4,t.DYNAMIC_DRAW,s)}if(i.lenFlags>0){let s=!0;e.flagsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,i.flags.slice(0,i.lenFlags),i.lenFlags,4,t.DYNAMIC_DRAW,s),e.flags2Buf=new ArrayBuf(t,t.ARRAY_BUFFER,i.flags2.slice(0,i.lenFlags),i.lenFlags,4,t.DYNAMIC_DRAW,s)}if(i.lenPickColors>0){let s=!1;e.pickColorsBuf=new ArrayBuf(t,t.ARRAY_BUFFER,i.pickColors.slice(0,i.lenPickColors),i.lenPickColors,4,t.STATIC_DRAW,s)}i.lenIndices>0&&(e.indicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,i.indices.slice(0,i.lenIndices),i.lenIndices,1,t.STATIC_DRAW)),i.lenEdgeIndices>0&&(e.edgeIndicesBuf=new ArrayBuf(t,t.ELEMENT_ARRAY_BUFFER,i.edgeIndices.slice(0,i.lenEdgeIndices),i.lenEdgeIndices,1,t.STATIC_DRAW)),i.lenPositions=0,i.lenColors=0,i.lenNormals=0,i.lenFlags=0,i.lenPickColors=0,i.lenIndices=0,i.lenEdgeIndices=0,this._buffer=null,this._finalized=!0}initFlags(e,t){t&RENDER_FLAGS.VISIBLE&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&RENDER_FLAGS.HIGHLIGHTED&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&RENDER_FLAGS.XRAYED&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&RENDER_FLAGS.SELECTED&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&RENDER_FLAGS.EDGES&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&RENDER_FLAGS.PICKABLE&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),this._setFlags(e,t),this._setFlags2(e,t)}setVisible(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.VISIBLE?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t)}setHighlighted(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.HIGHLIGHTED?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t)}setXRayed(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.XRAYED?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t)}setSelected(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.SELECTED?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t)}setEdges(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.EDGES?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags2(e,t)}setClippable(e,t){if(!this._finalized)throw"Not finalized";this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.PICKABLE?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t)}setColor(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=2*e,r=4*this._portions[s],o=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(o),n=t[0],l=t[1],h=t[2],c=t[3];for(var d=0;d<o;d+=4)a[d+0]=n,a[d+1]=l,a[d+2]=h,a[d+3]=c;if(i){t[3]<255?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--)}this._state.colorsBuf.setData(a,r,o)}_setFlags(e,t){if(!this._finalized)throw"Not finalized";var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1];const o=this._scratchMemory.getUInt8Array(r);for(var a=t&RENDER_FLAGS.VISIBLE?255:0,n=t&RENDER_FLAGS.XRAYED?255:0,l=t&RENDER_FLAGS.HIGHLIGHTED?255:0,h=t&RENDER_FLAGS.SELECTED?255:0,c=0;c<r;c+=4)o[c+0]=a,o[c+1]=n,o[c+2]=l,o[c+3]=h;this._state.flagsBuf.setData(o,s,r)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=t&RENDER_FLAGS.CLIPPABLE?255:0,a=t&RENDER_FLAGS.EDGES?255:0,n=t&RENDER_FLAGS.PICKABLE?255:0;const l=this._scratchMemory.getUInt8Array(r);for(var h=0;h<r;h+=4)l[h+0]=o,l[h+1]=a,l[h+2]=n;this._state.flags2Buf.setData(l,s,r)}drawNormalFillOpaque(e){0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(e.withSAO?this._batchingRenderers.drawRendererWithSAO&&this._batchingRenderers.drawRendererWithSAO.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE):this._batchingRenderers.drawRenderer&&this._batchingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE))}drawNormalEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE)}drawNormalFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.drawRenderer&&this._batchingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawNormalTransparentEdges(e){0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawDepth(e){0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(e,this)}drawNormals(e){0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(e,this)}drawXRayedFillOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.fillRenderer&&this._batchingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.fillRenderer&&this._batchingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawHighlightedFillOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.fillRenderer&&this._batchingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.fillRenderer&&this._batchingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawSelectedFillOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.fillRenderer&&this._batchingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.fillRenderer&&this._batchingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawPickMesh(e){0!==this._numVisibleLayerPortions&&this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(e,this)}drawPickDepths(e){0!==this._numVisibleLayerPortions&&this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(e,this)}drawPickNormals(e){0!==this._numVisibleLayerPortions&&this._batchingRenderers.pickNormalsRenderer&&this._batchingRenderers.pickNormalsRenderer.drawLayer(e,this)}drawOcclusion(e){0!==this._numVisibleLayerPortions&&this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(e,this)}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=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()}}var quantizePositions=function(){const e=math.mat4(),t=math.mat4();return function(i,s,r,o,a){const n=r[0],l=r[1],h=r[2],c=r[3]-n,d=r[4]-l,u=r[5]-h,p=65525/c,m=65525/d,_=65525/u;let g;for(g=0;g<s;g+=3)o[g+0]=Math.floor((i[g+0]-n)*p),o[g+1]=Math.floor((i[g+1]-l)*m),o[g+2]=Math.floor((i[g+2]-h)*_);math.identityMat4(e),math.translationMat4v(r,e),math.identityMat4(t),math.scalingMat4v([c/65525,d/65525,u/65525],t),math.mulMat4(e,t,a)}}();function transformAndOctEncodeNormals(e,t,i,s,r){let o,a,n,l,h,c,d=new Float32Array([0,0,0,0]),u=new Float32Array([0,0,0,0]);for(c=0;c<i;c+=3)d[0]=t[c],d[1]=t[c+1],d[2]=t[c+2],math.transformVec3(e,d,u),math.normalizeVec3(u,u),n=o=octEncodeVec3$1(u,"floor","floor"),l=h=dot$1(u,a=octDecodeVec2$1(o)),(l=dot$1(u,a=octDecodeVec2$1(o=octEncodeVec3$1(u,"ceil","floor"))))>h&&(n=o,h=l),(l=dot$1(u,a=octDecodeVec2$1(o=octEncodeVec3$1(u,"floor","ceil"))))>h&&(n=o,h=l),(l=dot$1(u,a=octDecodeVec2$1(o=octEncodeVec3$1(u,"ceil","ceil"))))>h&&(n=o,h=l),s[r+c+0]=n[0],s[r+c+1]=n[1],s[r+c+2]=0;return r+=i}function octEncodeVec3$1(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 octDecodeVec2$1(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 dot$1(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}const InstancingDrawShaderSource=function(e,t){this.vertex=buildVertex$e(e),this.fragment=buildFragment$e(e,t)};function buildVertex$e(e){const t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r,o,a;const n=[];for(n.push("// Instancing geometry drawing vertex shader"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),n.push("attribute vec2 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),s&&n.push("attribute vec4 flags2;"),n.push("attribute vec4 modelMatrixCol0;"),n.push("attribute vec4 modelMatrixCol1;"),n.push("attribute vec4 modelMatrixCol2;"),n.push("attribute vec4 modelNormalMatrixCol0;"),n.push("attribute vec4 modelNormalMatrixCol1;"),n.push("attribute vec4 modelNormalMatrixCol2;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),n.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r<o;r++)"ambient"!==(a=i.lights[r]).type&&(n.push("uniform vec4 lightColor"+r+";"),"dir"===a.type&&n.push("uniform vec3 lightDir"+r+";"),"point"===a.type&&n.push("uniform vec3 lightPos"+r+";"),"spot"===a.type&&(n.push("uniform vec3 lightPos"+r+";"),n.push("uniform vec3 lightDir"+r+";")));for(n.push("vec3 octDecode(vec2 oct) {"),n.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push("    if (v.z < 0.0) {"),n.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);"),n.push("    }"),n.push("    return normalize(v);"),n.push("}"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vColor;"),n.push("void main(void) {"),n.push("bool visible      = (float(flags.x) > 0.0);"),n.push("bool xrayed       = (float(flags.y) > 0.0);"),n.push("bool highlighted  = (float(flags.z) > 0.0);"),n.push("bool selected     = (float(flags.w) > 0.0);"),n.push("bool transparent  = ((float(color.a) / 255.0) < 1.0);"),n.push(`if \n    (!visible || \n    (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n    (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n    (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),n.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),n.push("vec4 viewPosition  = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),n.push("vec3 viewNormal = normalize(vec4(worldNormal * viewNormalMatrix).xyz);"),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;"),r=0,o=i.lights.length;r<o;r++)if("ambient"!==(a=i.lights[r]).type){if("dir"===a.type)"view"===a.space?n.push("viewLightDir = normalize(lightDir"+r+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);");else if("point"===a.type)"view"===a.space?n.push("viewLightDir = normalize(lightPos"+r+" - viewPosition.xyz);"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightPos"+r+", 0.0)).xyz);");else{if("spot"!==a.type)continue;"view"===a.space?n.push("viewLightDir = normalize(lightDir"+r+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+r+".rgb * lightColor"+r+".a);")}return n.push("vColor = vec4(reflectedColor * ((lightAmbient.rgb * lightAmbient.a) + vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0)), float(color.a) / 255.0);"),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2;")),n.push("gl_Position = projMatrix * viewPosition;"),n.push("}"),n.push("}"),n}function buildFragment$e(e,t){const i=e._sectionPlanesState;let s,r;const o=i.sectionPlanes.length>0,a=[];if(a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4      uSAOParams;"),a.push("const float       packUpscale = 256. / 255.;"),a.push("const float       unpackDownScale = 255. / 256.;"),a.push("const vec3        packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),a.push("const vec4        unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push("    return dot( v, unPackFactors );"),a.push("}")),o)for(a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),s=0,r=i.sectionPlanes.length;s<r;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("varying vec4 vColor;"),a.push("void main(void) {"),o){for(a.push("  bool clippable = (float(vFlags2.x) > 0.0);"),a.push("  if (clippable) {"),a.push("  float dist = 0.0;"),s=0,r=i.sectionPlanes.length;s<r;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push("   dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return t?(a.push("   float viewportWidth     = uSAOParams[0];"),a.push("   float viewportHeight    = uSAOParams[1];"),a.push("   float blendCutoff       = uSAOParams[2];"),a.push("   float blendFactor       = uSAOParams[3];"),a.push("   vec2 uv                 = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push("   float ambient           = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push("   gl_FragColor            = vec4(vColor.rgb * ambient, vColor.a);")):a.push("    gl_FragColor           = vColor;"),a.push("}"),a}const tempVec4$2=math.vec4();class InstancingDrawRenderer{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._shaderSource=new InstancingDrawShaderSource(this._scene),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=t.model,r=s.scene.canvas.gl,o=t._state,a=this._instanceExt;!this._program&&(this._allocate(),this.errors)||(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.uniform1i(this._uRenderPass,i),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),r.uniformMatrix4fv(this._uViewMatrix,!1,s.viewMatrix),r.uniformMatrix4fv(this._uViewNormalMatrix,!1,s.viewNormalMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0.bindArrayBuffer(o.modelNormalMatrixCol0Buf),this._aModelNormalMatrixCol1.bindArrayBuffer(o.modelNormalMatrixCol1Buf),this._aModelNormalMatrixCol2.bindArrayBuffer(o.modelNormalMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aNormal.bindArrayBuffer(o.normalsBuf),this._aColor.bindArrayBuffer(o.colorsBuf),a.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1)),o.indicesBuf.bind(),a.drawElementsInstancedANGLE(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0,o.numInstances),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),a.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,0),a.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,0),a.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,0),a.vertexAttribDivisorANGLE(this._aColor.location,0),a.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&a.vertexAttribDivisorANGLE(this._aFlags2.location,0))}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState,s=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelNormalMatrix=r.getLocation("modelNormalMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uViewNormalMatrix=r.getLocation("viewNormalMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const o=i.lights;let a;for(var n=0,l=o.length;n<l;n++)switch((a=o[n]).type){case"ambient":this._uLightAmbient[n]=r.getLocation("lightAmbient");break;case"dir":this._uLightColor[n]=r.getLocation("lightColor"+n),this._uLightPos[n]=null,this._uLightDir[n]=r.getLocation("lightDir"+n);break;case"point":this._uLightColor[n]=r.getLocation("lightColor"+n),this._uLightPos[n]=r.getLocation("lightPos"+n),this._uLightDir[n]=null,this._uLightAttenuation[n]=r.getLocation("lightAttenuation"+n);break;case"spot":this._uLightColor[n]=r.getLocation("lightColor"+n),this._uLightPos[n]=r.getLocation("lightPos"+n),this._uLightDir[n]=r.getLocation("lightDir"+n),this._uLightAttenuation[n]=r.getLocation("lightAttenuation"+n)}this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+e),pos:r.getLocation("sectionPlanePos"+e),dir:r.getLocation("sectionPlaneDir"+e)});this._aPosition=r.getAttribute("position"),this._aNormal=r.getAttribute("normal"),this._aColor=r.getAttribute("color"),this._aFlags=r.getAttribute("flags"),this._aFlags2=r.getAttribute("flags2"),this._aModelMatrixCol0=r.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=r.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=r.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=r.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=r.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=r.getAttribute("modelNormalMatrixCol2"),this._uSAOEnabled=r.getLocation("uSAOEnabled"),this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=r.getLocation("uSAOParams")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState,o=t._sectionPlanesState,a=r.lights;let n;s.bind();const l=t.camera;i.uniformMatrix4fv(this._uProjMatrix,!1,l._project._state.matrix);for(let e=0,t=a.length;e<t;e++)n=a[e],this._uLightAmbient[e]?i.uniform4f(this._uLightAmbient[e],n.color[0],n.color[1],n.color[2],n.intensity):(this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],n.color[0],n.color[1],n.color[2],n.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],n.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],n.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],n.dir));if(o.sectionPlanes.length>0){const e=t._sectionPlanesState.sectionPlanes;let s,r,o,a,n;for(var h=0,c=this._uSectionPlanes.length;h<c;h++)r=(s=this._uSectionPlanes[h]).active,o=e[h],r&&i.uniform1i(r,o.active),(a=s.pos)&&i.uniform3fv(s.pos,o.pos),(n=s.dir)&&i.uniform3fv(s.dir,o.dir)}if(this._withSAO){const s=t.sao;if(s.possible){const t=i.drawingBufferWidth,r=i.drawingBufferHeight;tempVec4$2[0]=t,tempVec4$2[1]=r,tempVec4$2[2]=s.blendCutoff,tempVec4$2[3]=s.blendFactor,i.uniform4fv(this._uSAOParams,tempVec4$2),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingFillShaderSource=function(e){this.vertex=buildVertex$f(e),this.fragment=buildFragment$f(e)};function buildVertex$f(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing fill vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec4 flags;"),t&&i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),i.push("uniform vec4 color;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("bool visible      = (float(flags.x) > 0.0);"),i.push("bool xrayed       = (float(flags.y) > 0.0);"),i.push("bool highlighted  = (float(flags.z) > 0.0);"),i.push("bool selected     = (float(flags.w) > 0.0);"),i.push("bool transparent  = (color.a < 1.0);"),i.push(`if\n    (!visible ||\n    (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (transparent || xrayed)) || \n    (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} && (!transparent || xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) || \n    (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n    (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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);"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$f(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;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("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;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("gl_FragColor = color;"),s.push("}"),s}class InstancingFillRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingFillShaderSource(this._scene),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.canvas.gl,a=t._state,n=this._instanceExt;if(this._program||(this._allocate(t.model.scene),!this.errors)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),o.uniformMatrix4fv(this._uViewMatrix,!1,s.viewMatrix),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf,o.UNSIGNED_BYTE,!0),n.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(a.flags2Buf,o.UNSIGNED_BYTE,!0),n.vertexAttribDivisorANGLE(this._aFlags2.location,1)),a.indicesBuf.bind(),i===RENDER_PASSES.XRAYED){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;o.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===RENDER_PASSES.HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;o.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===RENDER_PASSES.SELECTED){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;o.uniform4f(this._uColor,t[0],t[1],t[2],i)}else o.uniform4fv(this._uColor,defaultColorize);n.drawElementsInstancedANGLE(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),n.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&n.vertexAttribDivisorANGLE(this._aFlags2.location,0)}}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;i.bind();const r=e.camera;r._state;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,n,l,h;for(var o=0,a=this._uSectionPlanes.length;o<a;o++)r=(s=this._uSectionPlanes[o]).active,n=i[o],r&&t.uniform1i(r,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingEdgesShaderSource=function(e){this.vertex=buildVertex$g(e),this.fragment=buildFragment$g(e)};function buildVertex$g(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing edges vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("uniform vec4 color;"),i.push("void main(void) {"),i.push("bool visible      = (float(flags.x) > 0.0);"),i.push("bool xrayed       = (float(flags.y) > 0.0);"),i.push("bool highlighted  = (float(flags.z) > 0.0);"),i.push("bool selected     = (float(flags.w) > 0.0);"),i.push("bool edges        = (float(flags2.y) > 0.0);"),i.push("bool transparent  = (color.a < 1.0);"),i.push(`if (\n    !visible ||\n    (renderPass == ${RENDER_PASSES.NORMAL_OPAQUE} && (!edges || transparent || xrayed)) ||\n    (renderPass == ${RENDER_PASSES.NORMAL_TRANSPARENT} &&  (!edges || !transparent || xrayed || highlighted || selected)) ||\n    (renderPass == ${RENDER_PASSES.XRAYED} && (!xrayed || highlighted || selected)) ||\n    (renderPass == ${RENDER_PASSES.HIGHLIGHTED} && !highlighted) ||\n    (renderPass == ${RENDER_PASSES.SELECTED} && !selected)) {`),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);"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$g(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0;let s,r;const o=[];if(o.push("// Instancing edges 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"),o.push("uniform vec4 color;"),i)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),s=0,r=t.sectionPlanes.length;s<r;s++)o.push("uniform bool sectionPlaneActive"+s+";"),o.push("uniform vec3 sectionPlanePos"+s+";"),o.push("uniform vec3 sectionPlaneDir"+s+";");if(o.push("void main(void) {"),i){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),s=0,r=t.sectionPlanes.length;s<r;s++)o.push("if (sectionPlaneActive"+s+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return o.push("gl_FragColor = color;"),o.push("}"),o}class InstancingEdgesRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingEdgesShaderSource(this._scene),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.canvas.gl,a=t._state,n=this._instanceExt;if(!this._program&&(this._allocate(t),this.errors))return;let l;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const h=(l=i===RENDER_PASSES.XRAYED?r.xrayMaterial._state:i===RENDER_PASSES.HIGHLIGHTED?r.highlightMaterial._state:i===RENDER_PASSES.SELECTED?r.selectedMaterial._state:r.edgeMaterial._state).edgeColor,c=l.edgeAlpha;o.uniform4f(this._uColor,h[0],h[1],h[2],c),e.lineWidth!==l.edgeWidth&&(o.lineWidth(l.edgeWidth),e.lineWidth=l.edgeWidth),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),o.uniformMatrix4fv(this._uViewMatrix,!1,s.viewMatrix),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf,o.UNSIGNED_BYTE,!0),n.vertexAttribDivisorANGLE(this._aFlags.location,1)),this._aFlags2&&(this._aFlags2.bindArrayBuffer(a.flags2Buf,o.UNSIGNED_BYTE,!0),n.vertexAttribDivisorANGLE(this._aFlags2.location,1)),a.edgeIndicesBuf.bind(),n.drawElementsInstancedANGLE(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&n.vertexAttribDivisorANGLE(this._aFlags2.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uColor=s.getLocation("color"),this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2")}_bindProgram(){const e=this._scene,t=e.canvas.gl;this._program.bind();const i=e.camera;i._state;if(t.uniformMatrix4fv(this._uProjMatrix,!1,i._project._state.matrix),e._sectionPlanesState.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let o,a,n,l,h;for(var s=0,r=this._uSectionPlanes.length;s<r;s++)a=(o=this._uSectionPlanes[s]).active,n=i[s],a&&t.uniform1i(a,n.active),(l=o.pos)&&t.uniform3fv(o.pos,n.pos),(h=o.dir)&&t.uniform3fv(o.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingPickMeshShaderSource=function(e){this.vertex=buildVertex$h(e),this.fragment=buildFragment$h(e)};function buildVertex$h(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry picking vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push("bool visible   = (float(flags.x) > 0.0);"),i.push("bool pickable  = (float(flags2.z) > 0.0);"),i.push("if ((!pickInvisible && !visible) || !pickable) {"),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);"),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("vFlags2 = flags2;")),i.push("  gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$h(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push("gl_FragColor = vPickColor; "),s.push("}"),s}class InstancingPickMeshRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickMeshShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state,o=this._instanceExt;!this._program&&(this._allocate(),this.errors)||(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPickColor.bindArrayBuffer(r.pickColorsBuf),o.vertexAttribDivisorANGLE(this._aPickColor.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),o.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(r.flags2Buf),o.vertexAttribDivisorANGLE(this._aFlags2.location,1)),r.indicesBuf.bind(),o.drawElementsInstancedANGLE(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),o.vertexAttribDivisorANGLE(this._aPickColor.location,0),o.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&o.vertexAttribDivisorANGLE(this._aFlags2.location,0))}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aPickColor=s.getAttribute("pickColor"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=(t._lightsState,t._sectionPlanesState);s.bind();const o=t.camera;o._state;if(i.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),i.uniform1i(this._uPickInvisible,e.pickInvisible),r.sectionPlanes.length>0){const e=t._sectionPlanesState.sectionPlanes;let s,r,o,l,h;for(var a=0,n=this._uSectionPlanes.length;a<n;a++)r=(s=this._uSectionPlanes[a]).active,o=e[a],r&&i.uniform1i(r,o.active),(l=s.pos)&&i.uniform3fv(s.pos,o.pos),(h=s.dir)&&i.uniform3fv(s.dir,o.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingPickDepthShaderSource=function(e){this.vertex=buildVertex$i(e),this.fragment=buildFragment$i(e)};function buildVertex$i(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry depth vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible   = (float(flags.x) > 0.0);"),i.push("bool pickable  = (float(flags2.z) > 0.0);"),i.push("if ((!pickInvisible && !visible) || !pickable) {"),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);"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&i.push("  vWorldPosition = worldPosition;"),i.push("  vViewPosition = viewPosition;"),i.push("  gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$i(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),s.push("uniform float zNear;"),s.push("uniform float zFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying 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("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push("    float zNormalizedDepth = abs((zNear + vViewPosition.z) / (zFar - zNear));"),s.push("    gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}class InstancingPickDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=s.camera.project._state;r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix),r.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.uniform1f(this._uZNear,n.near),r.uniform1f(this._uZFar,n.far),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1)),o.indicesBuf.bind(),a.drawElementsInstancedANGLE(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0,o.numInstances),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),a.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&a.vertexAttribDivisorANGLE(this._aFlags2.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._uZNear=s.getLocation("zNear"),this._uZFar=s.getLocation("zFar")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;if(i.bind(),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,a,n,l,h;for(var r=0,o=this._uSectionPlanes.length;r<o;r++)a=(s=this._uSectionPlanes[r]).active,n=i[r],a&&t.uniform1i(a,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingPickNormalsShaderSource=function(e){this.vertex=buildVertex$j(e),this.fragment=buildFragment$j(e)};function buildVertex$j(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry normals vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec2 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("attribute vec4 modelNormalMatrixCol0;"),i.push("attribute vec4 modelNormalMatrixCol1;"),i.push("attribute vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("bool visible   = (float(flags.x) > 0.0);"),i.push("bool pickable  = (float(flags2.z) > 0.0);"),i.push("  if ((!pickInvisible && !visible) || !pickable) {"),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);"),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("  gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$j(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec3 vWorldNormal;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push("    gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}class InstancingPickNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingPickNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state,o=this._instanceExt;!this._program&&(this._allocate(t),this.errors)||(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniform1i(this._uPickInvisible,e.pickInvisible),s.uniformMatrix4fv(this._uViewMatrix,!1,e.pickViewMatrix?i.getPickViewMatrix(e.pickViewMatrix):i.viewMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0.bindArrayBuffer(r.modelNormalMatrixCol0Buf),this._aModelNormalMatrixCol1.bindArrayBuffer(r.modelNormalMatrixCol1Buf),this._aModelNormalMatrixCol2.bindArrayBuffer(r.modelNormalMatrixCol2Buf),o.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,1),o.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,1),o.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aNormal.bindArrayBuffer(r.normalsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),o.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(r.flags2Buf),o.vertexAttribDivisorANGLE(this._aFlags2.location,1)),r.indicesBuf.bind(),o.drawElementsInstancedANGLE(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),o.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,0),o.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,0),o.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,0),o.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&o.vertexAttribDivisorANGLE(this._aFlags2.location,0))}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aNormal=s.getAttribute("normal"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),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")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;if(i.bind(),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,a,n,l,h;for(var r=0,o=this._uSectionPlanes.length;r<o;r++)a=(s=this._uSectionPlanes[r]).active,n=i[r],a&&t.uniform1i(a,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingOcclusionShaderSource=function(e){this.vertex=buildVertex$k(e),this.fragment=buildFragment$k(e)};function buildVertex$k(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing occlusion vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),t&&i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible   = (float(flags.x) > 0.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);"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&i.push("  vWorldPosition = worldPosition;"),i.push("  vViewPosition = viewPosition;"),i.push("  gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$k(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec4 vViewPosition;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}class InstancingOcclusionRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingOcclusionShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state,o=this._instanceExt;!this._program&&(this._allocate(),this.errors)||(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),s.uniformMatrix4fv(this._uViewMatrix,!1,i.viewMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aColor&&(this._aColor.bindArrayBuffer(r.colorsBuf),o.vertexAttribDivisorANGLE(this._aColor.location,1)),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),o.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(r.flags2Buf),o.vertexAttribDivisorANGLE(this._aFlags2.location,1)),r.indicesBuf.bind(),o.drawElementsInstancedANGLE(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),this._aColor&&o.vertexAttribDivisorANGLE(this._aColor.location,0),o.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&o.vertexAttribDivisorANGLE(this._aFlags2.location,0))}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;i.bind();const r=e.camera;r._state;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,n,l,h;for(var o=0,a=this._uSectionPlanes.length;o<a;o++)r=(s=this._uSectionPlanes[o]).active,n=i[o],r&&t.uniform1i(r,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingDepthShaderSource=function(e){this.vertex=buildVertex$l(e),this.fragment=buildFragment$l(e)};function buildVertex$l(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry depth drawing vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),t&&i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("bool visible      = (float(flags.x) > 0.0);"),i.push("bool xrayed       = (float(flags.y) > 0.0);"),i.push("bool transparent  = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent || xrayed) {"),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);"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("  vViewPosition = viewPosition;"),i.push("  gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$l(e){const t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Instancing geometry depth 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"),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("varying vec4 vViewPosition;"),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("void main(void) {"),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;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("    gl_FragColor = packDepthToRGBA( gl_FragCoord.z); "),o.push("}"),o}class InstancingDepthRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingDepthShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state,o=this._instanceExt;!this._program&&(this._allocate(),this.errors)||(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),s.uniformMatrix4fv(this._uViewMatrix,!1,i.viewMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aColor.bindArrayBuffer(r.colorsBuf),o.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(r.flagsBuf),o.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(r.flags2Buf),o.vertexAttribDivisorANGLE(this._aFlags2.location,1)),r.indicesBuf.bind(),o.drawElementsInstancedANGLE(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),o.vertexAttribDivisorANGLE(this._aColor.location,0),o.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&o.vertexAttribDivisorANGLE(this._aFlags2.location,0))}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;e.camera.project._state;i.bind();const r=e.camera;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,n,l,h;for(var o=0,a=this._uSectionPlanes.length;o<a;o++)r=(s=this._uSectionPlanes[o]).active,n=i[o],r&&t.uniform1i(r,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const InstancingNormalsShaderSource=function(e){this.vertex=buildVertex$m(e),this.fragment=buildFragment$m(e)};function buildVertex$m(e){const t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry depth drawing vertex shader"),i.push("attribute vec3 position;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),t&&i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),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("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("bool visible      = (float(flags.x) > 0.0);"),i.push("bool xrayed       = (float(flags.y) > 0.0);"),i.push("bool transparent  = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent || xrayed) {"),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);"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("  vec4 worldNormal    = 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("  gl_Position = projMatrix * viewPosition;"),i.push("}"),i.push("}"),i}function buildFragment$m(e){const t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(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"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push("    return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;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("    gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}class InstancingNormalsRenderer{constructor(e){this._scene=e,this._hash=this._getHash(),this._shaderSource=new InstancingNormalsShaderSource(this._scene),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene.canvas.gl,r=t._state,o=this._instanceExt;!this._program&&(this._allocate(t),this.errors)||(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),s.uniformMatrix4fv(this._uViewMatrix,!1,i.viewMatrix),s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aNormal.bindArrayBuffer(r.normalsBuf),this._aColor.bindArrayBuffer(r.colorsBuf),o.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(r.flagsBuf),o.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(r.flags2Buf),o.vertexAttribDivisorANGLE(this._aFlags2.location,1)),r.indicesBuf.bind(),o.drawElementsInstancedANGLE(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),o.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),o.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),o.vertexAttribDivisorANGLE(this._aColor.location,0),o.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&o.vertexAttribDivisorANGLE(this._aFlags2.location,0))}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Program(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,o=i.sectionPlanes.length;r<o;r++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+r),pos:s.getLocation("sectionPlanePos"+r),dir:s.getLocation("sectionPlaneDir"+r)});this._aPosition=s.getAttribute("position"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2&&(this._aFlags2=s.getAttribute("flags2")),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2")}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState;i.bind();const r=e.camera;if(t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),s.sectionPlanes.length>0){const i=e._sectionPlanesState.sectionPlanes;let s,r,n,l,h;for(var o=0,a=this._uSectionPlanes.length;o<a;o++)r=(s=this._uSectionPlanes[o]).active,n=i[o],r&&t.uniform1i(r,n.active),(l=s.pos)&&t.uniform3fv(s.pos,n.pos),(h=s.dir)&&t.uniform3fv(s.dir,n.dir)}}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class InstancingRenderers{constructor(e){this._scene=e}_compile(){this.drawRenderer&&!this.drawRenderer.getValid()&&(this.drawRenderer.destroy(),this.drawRenderer=null),this.drawRendererWithSAO&&!this.drawRendererWithSAO.getValid()&&(this.drawRendererWithSAO.destroy(),this.drawRendererWithSAO=null),this.depthRenderer&&!this.depthRenderer.getValid()&&(this.depthRenderer.destroy(),this.depthRenderer=null),this.normalsRenderer&&!this.normalsRenderer.getValid()&&(this.normalsRenderer.destroy(),this.normalsRenderer=null),this.fillRenderer&&!this.fillRenderer.getValid()&&(this.fillRenderer.destroy(),this.fillRenderer=null),this.edgesRenderer&&!this.edgesRenderer.getValid()&&(this.edgesRenderer.destroy(),this.edgesRenderer=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&&!this.pickNormalsRenderer.getValid()&&(this.pickNormalsRenderer.destroy(),this.pickNormalsRenderer=null),this.occlusionRenderer&&!this.occlusionRenderer.getValid()&&(this.occlusionRenderer.destroy(),this.occlusionRenderer=null),this._createRenderers()}_createRenderers(){if(this.drawRenderer||(this.drawRenderer=new InstancingDrawRenderer(this._scene)),!this.drawRendererWithSAO){const e=!0;this.drawRendererWithSAO=new InstancingDrawRenderer(this._scene,e)}this.fillRenderer||(this.fillRenderer=new InstancingFillRenderer(this._scene)),this.edgesRenderer||(this.edgesRenderer=new InstancingEdgesRenderer(this._scene)),this.pickMeshRenderer||(this.pickMeshRenderer=new InstancingPickMeshRenderer(this._scene)),this.pickDepthRenderer||(this.pickDepthRenderer=new InstancingPickDepthRenderer(this._scene)),this.pickNormalsRenderer||(this.pickNormalsRenderer=new InstancingPickNormalsRenderer(this._scene)),this.occlusionRenderer||(this.occlusionRenderer=new InstancingOcclusionRenderer(this._scene)),this.depthRenderer||(this.depthRenderer=new InstancingDepthRenderer(this._scene)),this.normalsRenderer||(this.normalsRenderer=new InstancingNormalsRenderer(this._scene))}_destroy(){this.drawRenderer.destroy(),this.drawRendererWithSAO.destroy(),this.depthRenderer.destroy(),this.normalsRenderer.destroy(),this.fillRenderer.destroy(),this.edgesRenderer.destroy(),this.pickMeshRenderer.destroy(),this.pickDepthRenderer.destroy(),this.pickNormalsRenderer.destroy(),this.occlusionRenderer.destroy()}}const sceneInstancingRenderers={};function getInstancingRenderers(e){const t=e.id;let i=sceneInstancingRenderers[t];return i||(i=new InstancingRenderers(e),sceneInstancingRenderers[t]=i,i._compile(),e.on("compile",()=>{i._compile()}),e.on("destroyed",()=>{delete sceneInstancingRenderers[t],i._destroy()})),i}const bigIndicesSupported$2=WEBGL_INFO.SUPPORTED_EXTENSIONS.OES_element_index_uint,MAX_VERTS$1=bigIndicesSupported$2?5e6:65530,quantizedPositions=new Uint16Array(3*MAX_VERTS$1),compressedNormals=new Int8Array(3*MAX_VERTS$1),tempUint8Vec4=new Uint8Array(4),tempVec3a$2=math.vec4([0,0,0,1]),tempVec3b$2=math.vec4([0,0,0,1]),tempVec3c$2=math.vec4([0,0,0,1]);class InstancingLayer{constructor(e,t){this._instancingRenderers=getInstancingRenderers(e.scene),this.model=e,this._aabb=math.collapseAABB3();var i,s=t.primitive||"triangles";const r=e.scene.canvas.gl;switch(s){case"points":i=r.POINTS;break;case"lines":i=r.LINES;break;case"line-loop":i=r.LINE_LOOP;break;case"line-strip":i=r.LINE_STRIP;break;case"triangles":i=r.TRIANGLES;break;case"triangle-strip":i=r.TRIANGLE_STRIP;break;case"triangle-fan":i=r.TRIANGLE_FAN;break;default:e.error(`Unsupported value for 'primitive': '${s}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),i=r.TRIANGLES,s="triangles"}var o={primitiveName:s,primitive:i,positionsDecodeMatrix:math.mat4(),numInstances:0,obb:math.OBB3()};const a=!!t.positionsDecodeMatrix;if(t.positions)if(a){let e=!1;o.positionsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,t.positions,t.positions.length,3,r.STATIC_DRAW,e),o.positionsDecodeMatrix.set(t.positionsDecodeMatrix);let i=math.collapseAABB3();math.expandAABB3Points3(i,t.positions),geometryCompressionUtils.decompressAABB(i,o.positionsDecodeMatrix),math.AABB3ToOBB3(i,o.obb)}else{let e=t.positions.length,i=math.collapseAABB3();math.expandAABB3Points3(i,t.positions),math.AABB3ToOBB3(i,o.obb),quantizePositions$1(t.positions,e,i,quantizedPositions,o.positionsDecodeMatrix);let s=!1;o.positionsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,quantizedPositions,e,3,r.STATIC_DRAW,s)}if(t.normals)if(a){let e=!0;o.normalsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,t.normals,t.normals.length,3,r.STATIC_DRAW,e)}else{var n=octEncodeNormals(t.normals,t.normals.length,compressedNormals,0);let e=!0;o.normalsBuf=new ArrayBuf(r,r.ARRAY_BUFFER,compressedNormals,n,3,r.STATIC_DRAW,e)}t.indices&&(o.indicesBuf=new ArrayBuf(r,r.ELEMENT_ARRAY_BUFFER,bigIndicesSupported$2?new Uint32Array(t.indices):new Uint16Array(t.indices),t.indices.length,1,r.STATIC_DRAW));var l=t.edgeIndices;l||(l=buildEdgeIndices(t.positions,t.indices,null,10)),o.edgeIndicesBuf=new ArrayBuf(r,r.ELEMENT_ARRAY_BUFFER,bigIndicesSupported$2?new Uint32Array(l):new Uint16Array(l),l.length,1,r.STATIC_DRAW),this._state=new RenderState(o),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this.numIndices=t.indices?t.indices.length/3:0,this._flags=[],this._flags2=[],this._colors=[],this._pickColors=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._finalized=!1}createPortion(e,t,i,s,r,o,a){if(this._finalized)throw"Already finalized";var n=e&RENDER_FLAGS.VISIBLE?255:0,l=e&RENDER_FLAGS.XRAYED?255:0,h=e&RENDER_FLAGS.HIGHLIGHTED?255:0,c=e&RENDER_FLAGS.HIGHLIGHTED?255:0,d=e&RENDER_FLAGS.CLIPPABLE?255:0,u=e&RENDER_FLAGS.EDGES?255:0,p=e&RENDER_FLAGS.PICKABLE?255:0;this._flags.push(n),this._flags.push(l),this._flags.push(h),this._flags.push(c),this._flags2.push(d),this._flags2.push(u),this._flags2.push(p),this._flags2.push(0),n&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),l&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),h&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),c&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),u&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),p&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++);const m=t[0],_=t[1],g=t[2];t[3];i<255&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._colors.push(m),this._colors.push(_),this._colors.push(g),this._colors.push(i),this._modelMatrixCol0.push(s[0]),this._modelMatrixCol0.push(s[4]),this._modelMatrixCol0.push(s[8]),this._modelMatrixCol0.push(s[12]),this._modelMatrixCol1.push(s[1]),this._modelMatrixCol1.push(s[5]),this._modelMatrixCol1.push(s[9]),this._modelMatrixCol1.push(s[13]),this._modelMatrixCol2.push(s[2]),this._modelMatrixCol2.push(s[6]),this._modelMatrixCol2.push(s[10]),this._modelMatrixCol2.push(s[14]);let f=math.transposeMat4(s,math.mat4()),v=math.inverseMat4(f);this._modelNormalMatrixCol0.push(v[0]),this._modelNormalMatrixCol0.push(v[4]),this._modelNormalMatrixCol0.push(v[8]),this._modelNormalMatrixCol0.push(v[12]),this._modelNormalMatrixCol1.push(v[1]),this._modelNormalMatrixCol1.push(v[5]),this._modelNormalMatrixCol1.push(v[9]),this._modelNormalMatrixCol1.push(v[13]),this._modelNormalMatrixCol2.push(v[2]),this._modelNormalMatrixCol2.push(v[6]),this._modelNormalMatrixCol2.push(v[10]),this._modelNormalMatrixCol2.push(v[14]),this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]),math.collapseAABB3(o);for(var b=this._state.obb,y=b.length,M=0;M<y;M+=4)tempVec3a$2[0]=b[M+0],tempVec3a$2[1]=b[M+1],tempVec3a$2[2]=b[M+2],math.transformPoint4(s,tempVec3a$2,tempVec3b$2),r?(math.transformPoint4(r,tempVec3b$2,tempVec3c$2),math.expandAABB3Point3(o,tempVec3c$2)):math.expandAABB3Point3(o,tempVec3b$2);this._state.numInstances++;var w=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,w}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl;if(this._colors.length>0){let t=!1;this._state.colorsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(this._flags.length>0){let t=!0;this._state.flagsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._flags),this._flags.length,4,e.DYNAMIC_DRAW,t),this._state.flags2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._flags2),this._flags2.length,4,e.DYNAMIC_DRAW,t),this._flags=[],this._flags2=[]}if(this._modelMatrixCol0.length>0){let t=!1;this._state.modelMatrixCol0Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._state.modelNormalMatrixCol0Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol1Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol2Buf=new ArrayBuf(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[]}if(this._pickColors.length>0){let t=!1;this._state.pickColorsBuf=new ArrayBuf(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._finalized=!0}initFlags(e,t){t&RENDER_FLAGS.VISIBLE&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&RENDER_FLAGS.HIGHLIGHTED&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&RENDER_FLAGS.XRAYED&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&RENDER_FLAGS.SELECTED&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&RENDER_FLAGS.EDGES&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&RENDER_FLAGS.PICKABLE&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),this._setFlags(e,t),this._setFlags2(e,t)}setVisible(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.VISIBLE?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t)}setHighlighted(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.HIGHLIGHTED?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t)}setXRayed(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.XRAYED?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t)}setSelected(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.SELECTED?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t)}setEdges(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.EDGES?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags2(e,t)}setClippable(e,t){if(!this._finalized)throw"Not finalized";this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t){if(!this._finalized)throw"Not finalized";t&RENDER_FLAGS.PICKABLE?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t)}setColor(e,t,i=!1){if(!this._finalized)throw"Not finalized";if(tempUint8Vec4[0]=t[0],tempUint8Vec4[1]=t[1],tempUint8Vec4[2]=t[2],tempUint8Vec4[3]=t[3],i){t[3]<255?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--)}this._state.colorsBuf.setData(tempUint8Vec4,4*e,4)}_setFlags(e,t){if(!this._finalized)throw"Not finalized";var i=t&RENDER_FLAGS.VISIBLE?255:0,s=t&RENDER_FLAGS.XRAYED?255:0,r=t&RENDER_FLAGS.HIGHLIGHTED?255:0,o=t&RENDER_FLAGS.SELECTED?255:0;tempUint8Vec4[0]=i,tempUint8Vec4[1]=s,tempUint8Vec4[2]=r,tempUint8Vec4[3]=o,this._state.flagsBuf.setData(tempUint8Vec4,4*e,4)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";var i=t&RENDER_FLAGS.CLIPPABLE?255:0,s=t&RENDER_FLAGS.EDGES?255:0,r=t&RENDER_FLAGS.PICKABLE?255:0;tempUint8Vec4[0]=i,tempUint8Vec4[1]=s,tempUint8Vec4[2]=r,this._state.flags2Buf.setData(tempUint8Vec4,4*e,4)}drawNormalFillOpaque(e){0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(e.withSAO?this._instancingRenderers.drawRendererWithSAO&&this._instancingRenderers.drawRendererWithSAO.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE):this._instancingRenderers.drawRenderer&&this._instancingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE))}drawNormalEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_OPAQUE)}drawNormalFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.drawRenderer&&this._instancingRenderers.drawRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawNormalTransparentEdges(e){0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.NORMAL_TRANSPARENT)}drawDepth(e){0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(e,this)}drawNormals(e){0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(e,this)}drawXRayedFillOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawXRayedEdgesTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.XRAYED)}drawHighlightedFillOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawHighlightedEdgesTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.HIGHLIGHTED)}drawSelectedFillOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesOpaque(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedFillTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.fillRenderer&&this._instancingRenderers.fillRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawSelectedEdgesTransparent(e){0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(e,this,RENDER_PASSES.SELECTED)}drawPickMesh(e){0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(e,this)}drawPickDepths(e){0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(e,this)}drawPickNormals(e){0!==this._numVisibleLayerPortions&&this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(e,this)}drawOcclusion(e){0!==this._numVisibleLayerPortions&&this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(e,this)}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=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.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}var quantizePositions$1=function(){const e=math.mat4(),t=math.mat4(),i=math.vec3();return function(s,r,o,a,n){const l=o[0],h=o[1],c=o[2],d=o[3],u=o[4],p=o[5],m=o[3]-l,_=o[4]-h,g=o[5]-c,f=d!==l?65535/(d-l):0,v=u!==h?65535/(u-h):0,b=p!==c?65535/(p-c):0;let y;for(y=0;y<r;y+=3)a[y+0]=Math.floor((s[y+0]-l)*f),a[y+1]=Math.floor((s[y+1]-h)*v),a[y+2]=Math.floor((s[y+2]-c)*b);math.identityMat4(e),math.translationMat4v(o,e),math.identityMat4(t),i[0]=m/65535,i[1]=_/65535,i[2]=g/65535,math.scalingMat4v(i,t),math.mulMat4(e,t,n)}}();function octEncodeNormals(e,t,i,s){let r,o,a,n,l;for(let h=0;h<t;h+=3)a=r=octEncodeVec3$2(e,h,"floor","floor"),n=l=dot$2(e,h,o=octDecodeVec2$2(r)),(n=dot$2(e,h,o=octDecodeVec2$2(r=octEncodeVec3$2(e,h,"ceil","floor"))))>l&&(a=r,l=n),(n=dot$2(e,h,o=octDecodeVec2$2(r=octEncodeVec3$2(e,h,"floor","ceil"))))>l&&(a=r,l=n),(n=dot$2(e,h,o=octDecodeVec2$2(r=octEncodeVec3$2(e,h,"ceil","ceil"))))>l&&(a=r,l=n),i[s+h+0]=a[0],i[s+h+1]=a[1],i[s+h+2]=0;return s+=t}function octEncodeVec3$2(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=r,t=o;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 octDecodeVec2$2(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 dot$2(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const instancedArraysSupported=WEBGL_INFO.SUPPORTED_EXTENSIONS.ANGLE_instanced_arrays;var tempMat4$1=math.mat4();const defaultScale=math.vec3([1,1,1]),defaultPosition=math.vec3([0,0,0]),defaultRotation=math.vec3([0,0,0]),defaultQuaternion=math.identityQuaternion();class PerformanceModel extends Component{constructor(e,t={}){super(e,t),this._aabb=math.collapseAABB3(),this._layerList=[],this._nodeList=[],this._lastDecodeMatrix=null,this._instancingLayers={},this._currentBatchingLayer=null,this._batchingBuffer=getBatchingBuffer(),this._batchingScratchMemory=getBatchingLayerScratchMemory(this),this._meshes={},this._nodes={},this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numEntities=0,this._numTriangles=0,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces,this._position=new Float32Array(t.position||[0,0,0]),this._rotation=new Float32Array(t.rotation||[0,0,0]),this._quaternion=new Float32Array(t.quaternion||[0,0,0,1]),t.rotation&&math.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=new Float32Array(t.scale||[1,1,1]),this._worldMatrix=math.mat4(),math.composeMat4(this._position,this._quaternion,this._scale,this._worldMatrix),this._worldNormalMatrix=math.mat4(),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=math.mat4(),this._viewNormalMatrix=math.mat4(),this._viewMatrixDirty=!0,this._worldMatrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",()=>{this._viewMatrixDirty=!0})}get isPerformanceModel(){return!0}get position(){return this._position}get rotation(){return this._rotation}get quaternion(){return this._quaternion}get scale(){return this._scale}get matrix(){return this._worldMatrix}get worldMatrix(){return this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrix}get viewMatrix(){return this._viewMatrix?(this._viewMatrixDirty&&(math.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),math.inverseMat4(this._viewMatrix,this._viewNormalMatrix),math.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}get viewNormalMatrix(){return this._viewNormalMatrix?(this._viewMatrixDirty&&(math.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),math.inverseMat4(this._viewMatrix,this._viewNormalMatrix),math.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}createGeometry(e){if(!instancedArraysSupported)return void this.error("WebGL instanced arrays not supported");const t=e.id;if(void 0===t||null===t)return void this.error("Config missing: id");if(this._instancingLayers[t])return void this.error("Geometry already created: "+t);const i=new InstancingLayer(this,e);this._instancingLayers[t]=i,this._layerList.push(i),this.numGeometries++,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0}createMesh(e){let t=e.id;if(void 0===t||null===t)return void this.error("Config missing: id");if(this._meshes[t])return void this.error("PerformanceModel already has a Mesh with this ID: "+t);const i=e.geometryId,s=void 0!==i;if(s){if(!instancedArraysSupported)return void this.error("WebGL instanced arrays not supported");if(!this._instancingLayers[i])return void this.error("Geometry not found: "+i+" - ensure that you create it first with createGeometry()")}var r,o;const a=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],n=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;n<255&&this.numTransparentLayerPortions++;var l=new PerformanceMesh(this,t,a,n),h=l.pickId;const c=new Uint8Array([255&h,h>>8&255,h>>16&255,h>>24&255]),d=math.collapseAABB3();if(s){let t,s=this._worldMatrixNonIdentity?this._worldMatrix:null;if(e.matrix)t=e.matrix;else{const i=e.scale||defaultScale,s=e.position||defaultPosition,r=e.rotation||defaultRotation;math.eulerToQuaternion(r,"XYZ",defaultQuaternion),t=math.composeMat4(s,defaultQuaternion,i,tempMat4$1)}var u=this._instancingLayers[i];r=u,o=u.createPortion(0,a,n,t,s,d,c),math.expandAABB3(this._aabb,d);const h=Math.round(u.numIndices/3);this._numTriangles+=h,l.numTriangles=h}else{var p=e.primitive||"triangles";"points"!==p&&"lines"!==p&&"line-loop"!==p&&"line-strip"!==p&&"triangles"!==p&&"triangle-strip"!==p&&"triangle-fan"!==p&&(this.error(`Unsupported value for 'primitive': '${p}' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'.`),p="triangles");var m=e.indices,_=e.edgeIndices,g=e.positions;if(!g)return this.error("Config missing: positions (no meshIds provided, so expecting geometry arrays instead)"),null;var f=e.normals;if(!f)return this.error("Config missing: normals (no meshIds provided, so expecting geometry arrays instead)"),null;if(!_&&!m)return this.error("Config missing: must have one or both of indices and edgeIndices  (no meshIds provided, so expecting geometry arrays instead)"),null;let t;e.positionsDecodeMatrix&&(this._lastDecodeMatrix?math.compareMat4(this._lastDecodeMatrix,e.positionsDecodeMatrix)||(this._currentBatchingLayer&&(this._currentBatchingLayer.finalize(),this._currentBatchingLayer=null),this._lastDecodeMatrix.set(e.positionsDecodeMatrix)):this._lastDecodeMatrix=math.mat4(e.positionsDecodeMatrix)),this._currentBatchingLayer&&(this._currentBatchingLayer.canCreatePortion(g.length,m.length)||(this._currentBatchingLayer.finalize(),this._currentBatchingLayer=null)),this._currentBatchingLayer||(this._currentBatchingLayer=new BatchingLayer(this,{primitive:"triangles",buffer:this._batchingBuffer,scratchMemory:this._batchingScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix}),this._layerList.push(this._currentBatchingLayer)),r=this._currentBatchingLayer,!_&&m&&(_=buildEdgeIndices(g,m,null,10));let i=this._worldMatrixNonIdentity?this._worldMatrix:null;if(!e.positionsDecodeMatrix)if(e.matrix)t=e.matrix;else{const i=e.scale||defaultScale,s=e.position||defaultPosition,r=e.rotation||defaultRotation;math.eulerToQuaternion(r,"XYZ",defaultQuaternion),t=math.composeMat4(s,defaultQuaternion,i,tempMat4$1)}o=this._currentBatchingLayer.createPortion(g,f,m,_,0,a,n,t,i,d,c),math.expandAABB3(this._aabb,d),this.numGeometries++;const s=Math.round(m.length/3);this._numTriangles+=s,l.numTriangles=s}l.parent=null,l._layer=r,l._portionId=o,l.aabb=d,this._meshes[t]=l}createEntity(e){let t=e.id;void 0===t?t=math.createUUID():this.scene.components[t]&&(this.error("Scene already has a Component with this ID: "+t+" - will assign random ID"),t=math.createUUID());const i=e.meshIds;if(void 0===i)return void this.error("Config missing: meshIds");var s,r,o,a,n=[];for(s=0,r=i.length;s<r;s++)o=i[s],(a=this._meshes[o])?a.parent?this.error("Mesh with ID "+o+" already belongs to object with ID "+a.parent.id+" - ignoring this mesh"):n.push(a):this.error("Mesh with this ID not found: "+o+" - ignoring this mesh");var l,h=0;if(this._visible&&!1!==e.visible&&(h|=RENDER_FLAGS.VISIBLE),this._pickable&&!1!==e.pickable&&(h|=RENDER_FLAGS.PICKABLE),this._clippable&&!1!==e.clippable&&(h|=RENDER_FLAGS.CLIPPABLE),this._collidable&&!1!==e.collidable&&(h|=RENDER_FLAGS.COLLIDABLE),this._edges&&!1!==e.edges&&(h|=RENDER_FLAGS.EDGES),this._xrayed&&!1!==e.xrayed&&(h|=RENDER_FLAGS.XRAYED),this._highlighted&&!1!==e.highlighted&&(h|=RENDER_FLAGS.HIGHLIGHTED),this._selected&&!1!==e.selected&&(h|=RENDER_FLAGS.SELECTED),1===n.length)l=n[0].aabb;else for(l=math.collapseAABB3(),s=0,r=n.length;s<r;s++)math.expandAABB3(l,n[s].aabb);const c=new PerformanceNode(this,e.isObject,t,n,h,l);return this._nodeList.push(c),this._nodes[t]=c,this.numEntities++,c}finalize(){this._currentBatchingLayer&&(this._currentBatchingLayer.finalize(),this._currentBatchingLayer=null),this._batchingBuffer&&(putBatchingBuffer(this._batchingBuffer),this._batchingBuffer=null);for(const e in this._instancingLayers)this._instancingLayers.hasOwnProperty(e)&&this._instancingLayers[e].finalize();for(var e=0,t=this._nodeList.length;e<t;e++){this._nodeList[e]._finalize()}this.glRedraw(),this.scene._aabbDirty=!0}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get backfaces(){return this._backfaces}get entityList(){return this._nodeList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){return this._aabb}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].visible=e;this.glRedraw()}get visible(){return this.numVisibleLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].xrayed=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].highlighted=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].selected=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].edges=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set culled(e){e=!!e,this._culled=e,this.glRedraw()}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].clippable=e;this.glRedraw()}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].pickable=e}get pickable(){return this._pickable}set colorize(e){this._colorize=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].colorize=e}get colorize(){return this._colorize}set opacity(e){this._opacity=e;for(var t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].opacity=e}get opacity(){return this._opacity}set castsShadow(e){}get castsShadow(){return!1}set receivesShadow(e){}get receivesShadow(){return!1}get saoEnabled(){return this._saoEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}stateSortCompare(e,t){}getRenderFlags(e){if(e.reset(),0!==this.numVisibleLayerPortions){if(e.normalFillOpaque=!0,this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedFillTransparent=!0:e.xrayedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){const t=this.scene.edgeMaterial._state;t.edges&&(t.alpha<1?e.normalEdgesTransparent=!0:e.normalEdgesOpaque=!0)}if(this.numTransparentLayerPortions>0&&(e.normalFillTransparent=!0),this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedFillTransparent=!0:e.selectedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedFillTransparent=!0:e.highlightedFillOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}drawNormalFillOpaque(e){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}for(let t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawNormalFillOpaque(e)}drawDepth(e){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawDepth(e)}drawNormals(e){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawNormals(e)}drawNormalEdgesOpaque(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawNormalEdgesOpaque(e)}drawNormalFillTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawNormalFillTransparent(e)}drawNormalEdgesTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawNormalEdgesTransparent(e)}drawXRayedFillOpaque(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawXRayedFillOpaque(e)}drawXRayedEdgesOpaque(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawXRayedEdgesOpaque(e)}drawXRayedFillTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawXRayedFillTransparent(e)}drawXRayedEdgesTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawXRayedEdgesTransparent(e)}drawHighlightedFillOpaque(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawHighlightedFillOpaque(e)}drawHighlightedEdgesOpaque(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawHighlightedEdgesOpaque(e)}drawHighlightedFillTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawHighlightedFillTransparent(e)}drawHighlightedEdgesTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawHighlightedEdgesTransparent(e)}drawSelectedFillOpaque(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawSelectedFillOpaque(e)}drawSelectedEdgesOpaque(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawSelectedEdgesOpaque(e)}drawSelectedFillTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawSelectedFillTransparent(e)}drawSelectedEdgesTransparent(e){for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawSelectedEdgesTransparent(e)}drawPickMesh(e){if(0!==this.numVisibleLayerPortions){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawPickMesh(e)}}drawPickDepths(e){if(0!==this.numVisibleLayerPortions){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawPickDepths(e)}}drawPickNormals(e){if(0!==this.numVisibleLayerPortions){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawPickNormals(e)}}drawOcclusion(e){if(0!==this.numVisibleLayerPortions){if(e.backfaces!==this.backfaces){const t=this.scene.canvas.gl;this.backfaces?t.disable(t.CULL_FACE):t.enable(t.CULL_FACE),e.backfaces=this.backfaces}for(var t=0,i=this._layerList.length;t<i;t++)this._layerList[t].drawOcclusion(e)}}destroy(){this._currentBatchingLayer&&(this._currentBatchingLayer.destroy(),this._currentBatchingLayer=null),this._batchingBuffer&&(putBatchingBuffer(this._batchingBuffer),this._batchingBuffer=null),this.scene.camera.off(this._onCameraViewMatrix);for(let e=0,t=this._layerList.length;e<t;e++)this._layerList[e].destroy();for(let e=0,t=this._nodeList.length;e<t;e++)this._nodeList[e]._destroy();this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),super.destroy()}}class XKTDefaultDataSource{constructor(){}getMetaModel(e,t,i){utils.loadJSON(e,e=>{t(e)},function(e){i(e)})}getXKT(e,t,i){var s=()=>{};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),s=new Uint8Array(e);for(var a=0;a<o.length;a++)s[a]=o.charCodeAt(a);t(e)}catch(e){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("getXKT error : "+s.response))},s.send(null)}}}const IFCObjectDefaults={IfcRoof:{colorize:[.837255,.203922,.270588]},IfcSlab:{colorize:[.637255,.603922,.670588]},IfcWall:{colorize:[.537255,.337255,.237255]},IfcWallStandardCase:{colorize:[.537255,.337255,.237255]},IfcCovering:{colorize:[.8470588235,.427450980392,0]},IfcDoor:{colorize:[.637255,.603922,.670588]},IfcStair:{colorize:[.637255,.603922,.670588]},IfcStairFlight:{colorize:[.637255,.603922,.670588]},IfcProxy:{colorize:[.137255,.403922,.870588]},IfcRamp:{colorize:[.8470588235,.427450980392,0]},IfcColumn:{colorize:[.137255,.403922,.870588]},IfcBeam:{colorize:[.137255,.403922,.870588]},IfcCurtainWall:{colorize:[.137255,.403922,.870588]},IfcPlate:{colorize:[.8470588235,.427450980392,0,.5],opacity:.3},IfcTransportElement:{colorize:[.8470588235,.427450980392,0]},IfcFooting:{colorize:[.8470588235,.427450980392,0]},IfcRailing:{colorize:[.137255,.403922,.870588]},IfcFurnishingElement:{colorize:[.137255,.403922,.870588]},IfcFurniture:{colorize:[.8470588235,.427450980392,0]},IfcSystemFurnitureElement:{colorize:[.8470588235,.427450980392,0]},IfcFlowSegment:{colorize:[.137255,.403922,.870588]},IfcFlowitting:{colorize:[.137255,.403922,.870588]},IfcFlowTerminal:{colorize:[.137255,.403922,.870588]},IfcFlowController:{colorize:[.8470588235,.427450980392,0]},IfcFlowFitting:{colorize:[.8470588235,.427450980392,0]},IfcDuctSegment:{colorize:[.8470588235,.427450980392,0]},IfcDistributionFlowElement:{colorize:[.8470588235,.427450980392,0]},IfcDuctFitting:{colorize:[.8470588235,.427450980392,0]},IfcLightFixture:{colorize:[.8470588235,.8470588235,.870588]},IfcAirTerminal:{colorize:[.8470588235,.427450980392,0]},IfcOpeningElement:{colorize:[.137255,.403922,.870588],pickable:!1,visible:!1},IfcSpace:{colorize:[.137255,.403922,.870588],pickable:!1,visible:!1,opacity:.5},IfcWindow:{colorize:[.137255,.403922,.870588],pickable:!0,opacity:.1},IfcBuildingElementProxy:{colorize:[.5,.5,.5]},IfcSite:{colorize:[.137255,.403922,.870588]},IfcMember:{colorize:[.8470588235,.427450980392,0]},DEFAULT:{colorize:[.5,.5,.5]}};!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).pako=e()}}(function(){return function(){return function e(t,i,s){function r(a,n){if(!i[a]){if(!t[a]){var l="function"==typeof require&&require;if(!n&&l)return l(a,!0);if(o)return o(a,!0);var h=new Error("Cannot find module '"+a+"'");throw h.code="MODULE_NOT_FOUND",h}var c=i[a]={exports:{}};t[a][0].call(c.exports,function(e){return r(t[a][1][e]||e)},c,c.exports,e,t,i,s)}return i[a].exports}for(var o="function"==typeof require&&require,a=0;a<s.length;a++)r(s[a]);return r}}()({1:[function(e,t,i){var s=e("./zlib/deflate"),r=e("./utils/common"),o=e("./utils/strings"),a=e("./zlib/messages"),n=e("./zlib/zstream"),l=Object.prototype.toString,h=0,c=-1,d=0,u=8;function p(e){if(!(this instanceof p))return new p(e);this.options=r.assign({level:c,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:d,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new n,this.strm.avail_out=0;var i=s.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==h)throw new Error(a[i]);if(t.header&&s.deflateSetHeader(this.strm,t.header),t.dictionary){var m;if(m="string"==typeof t.dictionary?o.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=s.deflateSetDictionary(this.strm,m))!==h)throw new Error(a[i]);this._dict_set=!0}}function m(e,t){var i=new p(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}p.prototype.push=function(e,t){var i,a,n=this.strm,c=this.options.chunkSize;if(this.ended)return!1;a=t===~~t?t:!0===t?4:0,"string"==typeof e?n.input=o.string2buf(e):"[object ArrayBuffer]"===l.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;do{if(0===n.avail_out&&(n.output=new r.Buf8(c),n.next_out=0,n.avail_out=c),1!==(i=s.deflate(n,a))&&i!==h)return this.onEnd(i),this.ended=!0,!1;0!==n.avail_out&&(0!==n.avail_in||4!==a&&2!==a)||("string"===this.options.to?this.onData(o.buf2binstring(r.shrinkBuf(n.output,n.next_out))):this.onData(r.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||0===n.avail_out)&&1!==i);return 4===a?(i=s.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===h):2!==a||(this.onEnd(h),n.avail_out=0,!0)},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=p,i.deflate=m,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,m(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,m(e,t)}},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(e,t,i){var s=e("./zlib/inflate"),r=e("./utils/common"),o=e("./utils/strings"),a=e("./zlib/constants"),n=e("./zlib/messages"),l=e("./zlib/zstream"),h=e("./zlib/gzheader"),c=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=s.inflateInit2(this.strm,t.windowBits);if(i!==a.Z_OK)throw new Error(n[i]);if(this.header=new h,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=s.inflateSetDictionary(this.strm,t.dictionary))!==a.Z_OK))throw new Error(n[i])}function u(e,t){var i=new d(t);if(i.push(e,!0),i.err)throw i.msg||n[i.err];return i.result}d.prototype.push=function(e,t){var i,n,l,h,d,u=this.strm,p=this.options.chunkSize,m=this.options.dictionary,_=!1;if(this.ended)return!1;n=t===~~t?t:!0===t?a.Z_FINISH:a.Z_NO_FLUSH,"string"==typeof e?u.input=o.binstring2buf(e):"[object ArrayBuffer]"===c.call(e)?u.input=new Uint8Array(e):u.input=e,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new r.Buf8(p),u.next_out=0,u.avail_out=p),(i=s.inflate(u,a.Z_NO_FLUSH))===a.Z_NEED_DICT&&m&&(i=s.inflateSetDictionary(this.strm,m)),i===a.Z_BUF_ERROR&&!0===_&&(i=a.Z_OK,_=!1),i!==a.Z_STREAM_END&&i!==a.Z_OK)return this.onEnd(i),this.ended=!0,!1;u.next_out&&(0!==u.avail_out&&i!==a.Z_STREAM_END&&(0!==u.avail_in||n!==a.Z_FINISH&&n!==a.Z_SYNC_FLUSH)||("string"===this.options.to?(l=o.utf8border(u.output,u.next_out),h=u.next_out-l,d=o.buf2string(u.output,l),u.next_out=h,u.avail_out=p-h,h&&r.arraySet(u.output,u.output,l,h,0),this.onData(d)):this.onData(r.shrinkBuf(u.output,u.next_out)))),0===u.avail_in&&0===u.avail_out&&(_=!0)}while((u.avail_in>0||0===u.avail_out)&&i!==a.Z_STREAM_END);return i===a.Z_STREAM_END&&(n=a.Z_FINISH),n===a.Z_FINISH?(i=s.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===a.Z_OK):n!==a.Z_SYNC_FLUSH||(this.onEnd(a.Z_OK),u.avail_out=0,!0)},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===a.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=d,i.inflate=u,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,u(e,t)},i.ungzip=u},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(e,t,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)r(i,s)&&(e[s]=i[s])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,i,s,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+s),r);else for(var o=0;o<s;o++)e[r+o]=t[i+o]},flattenChunks:function(e){var t,i,s,r,o,a;for(s=0,t=0,i=e.length;t<i;t++)s+=e[t].length;for(a=new Uint8Array(s),r=0,t=0,i=e.length;t<i;t++)o=e[t],a.set(o,r),r+=o.length;return a}},a={arraySet:function(e,t,i,s,r){for(var o=0;o<s;o++)e[r+o]=t[i+o]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,o)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,a))},i.setTyped(s)},{}],4:[function(e,t,i){var s=e("./common"),r=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var a=new s.Buf8(256),n=0;n<256;n++)a[n]=n>=252?6:n>=248?5:n>=240?4:n>=224?3:n>=192?2:1;function l(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var i="",a=0;a<t;a++)i+=String.fromCharCode(e[a]);return i}a[254]=a[254]=1,i.string2buf=function(e){var t,i,r,o,a,n=e.length,l=0;for(o=0;o<n;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=new s.Buf8(l),a=0,o=0;a<l;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|63&i):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|63&i):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new s.Buf8(e.length),i=0,r=t.length;i<r;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,s,r,o,n=t||e.length,h=new Array(2*n);for(s=0,i=0;i<n;)if((r=e[i++])<128)h[s++]=r;else if((o=a[r])>4)h[s++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&i<n;)r=r<<6|63&e[i++],o--;o>1?h[s++]=65533:r<65536?h[s++]=r:(r-=65536,h[s++]=55296|r>>10&1023,h[s++]=56320|1023&r)}return l(h,s)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0?t:0===i?t:i+a[e[i]]>t?i:t}},{"./common":3}],5:[function(e,t,i){t.exports=function(e,t,i,s){for(var r=65535&e|0,o=e>>>16&65535|0,a=0;0!==i;){i-=a=i>2e3?2e3:i;do{o=o+(r=r+t[s++]|0)|0}while(--a);r%=65521,o%=65521}return r|o<<16|0}},{}],6:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],7:[function(e,t,i){var s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,r){var o=s,a=r+i;e^=-1;for(var n=r;n<a;n++)e=e>>>8^o[255&(e^t[n])];return-1^e}},{}],8:[function(e,t,i){var s,r=e("../utils/common"),o=e("./trees"),a=e("./adler32"),n=e("./crc32"),l=e("./messages"),h=0,c=1,d=3,u=4,p=5,m=0,_=1,g=-2,f=-3,v=-5,b=-1,y=1,M=2,w=3,x=4,P=0,E=2,A=8,C=9,S=15,R=8,L=286,D=30,k=19,T=2*L+1,I=15,B=3,F=258,N=F+B+1,V=32,O=42,j=69,U=73,G=91,z=103,H=113,$=666,W=1,X=2,Y=3,q=4,K=3;function Z(e,t){return e.msg=l[t],t}function Q(e){return(e<<1)-(e>4?9:0)}function J(e){for(var t=e.length;--t>=0;)e[t]=0}function ee(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(r.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function te(e,t){o._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ee(e.strm)}function ie(e,t){e.pending_buf[e.pending++]=t}function se(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function re(e,t){var i,s,r=e.max_chain_length,o=e.strstart,a=e.prev_length,n=e.nice_match,l=e.strstart>e.w_size-N?e.strstart-(e.w_size-N):0,h=e.window,c=e.w_mask,d=e.prev,u=e.strstart+F,p=h[o+a-1],m=h[o+a];e.prev_length>=e.good_match&&(r>>=2),n>e.lookahead&&(n=e.lookahead);do{if(h[(i=t)+a]===m&&h[i+a-1]===p&&h[i]===h[o]&&h[++i]===h[o+1]){o+=2,i++;do{}while(h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&o<u);if(s=F-(u-o),o=u-F,s>a){if(e.match_start=t,a=s,s>=n)break;p=h[o+a-1],m=h[o+a]}}}while((t=d[t&c])>l&&0!=--r);return a<=e.lookahead?a:e.lookahead}function oe(e){var t,i,s,o,l,h,c,d,u,p,m=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=m+(m-N)){r.arraySet(e.window,e.window,m,m,0),e.match_start-=m,e.strstart-=m,e.block_start-=m,t=i=e.hash_size;do{s=e.head[--t],e.head[t]=s>=m?s-m:0}while(--i);t=i=m;do{s=e.prev[--t],e.prev[t]=s>=m?s-m:0}while(--i);o+=m}if(0===e.strm.avail_in)break;if(h=e.strm,c=e.window,d=e.strstart+e.lookahead,u=o,p=void 0,(p=h.avail_in)>u&&(p=u),i=0===p?0:(h.avail_in-=p,r.arraySet(c,h.input,h.next_in,p,d),1===h.state.wrap?h.adler=a(h.adler,c,p,d):2===h.state.wrap&&(h.adler=n(h.adler,c,p,d)),h.next_in+=p,h.total_in+=p,p),e.lookahead+=i,e.lookahead+e.insert>=B)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+B-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<B)););}while(e.lookahead<N&&0!==e.strm.avail_in)}function ae(e,t){for(var i,s;;){if(e.lookahead<N){if(oe(e),e.lookahead<N&&t===h)return W;if(0===e.lookahead)break}if(i=0,e.lookahead>=B&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-N&&(e.match_length=re(e,i)),e.match_length>=B)if(s=o._tr_tally(e,e.strstart-e.match_start,e.match_length-B),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=B){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else s=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(s&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=e.strstart<B-1?e.strstart:B-1,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}function ne(e,t){for(var i,s,r;;){if(e.lookahead<N){if(oe(e),e.lookahead<N&&t===h)return W;if(0===e.lookahead)break}if(i=0,e.lookahead>=B&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=B-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-N&&(e.match_length=re(e,i),e.match_length<=5&&(e.strategy===y||e.match_length===B&&e.strstart-e.match_start>4096)&&(e.match_length=B-1)),e.prev_length>=B&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-B,s=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-B),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=B-1,e.strstart++,s&&(te(e,!1),0===e.strm.avail_out))return W}else if(e.match_available){if((s=o._tr_tally(e,0,e.window[e.strstart-1]))&&te(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return W}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(s=o._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<B-1?e.strstart:B-1,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}function le(e,t,i,s,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=s,this.func=r}function he(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=E,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?O:H,e.adler=2===t.wrap?0:1,t.last_flush=h,o._tr_init(t),m):Z(e,g)}function ce(e){var t,i=he(e);return i===m&&((t=e.state).window_size=2*t.w_size,J(t.head),t.max_lazy_match=s[t.level].max_lazy,t.good_match=s[t.level].good_length,t.nice_match=s[t.level].nice_length,t.max_chain_length=s[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=B-1,t.match_available=0,t.ins_h=0),i}function de(e,t,i,s,o,a){if(!e)return g;var n=1;if(t===b&&(t=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),o<1||o>C||i!==A||s<8||s>15||t<0||t>9||a<0||a>x)return Z(e,g);8===s&&(s=9);var l=new function(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=A,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(2*T),this.dyn_dtree=new r.Buf16(2*(2*D+1)),this.bl_tree=new r.Buf16(2*(2*k+1)),J(this.dyn_ltree),J(this.dyn_dtree),J(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(I+1),this.heap=new r.Buf16(2*L+1),J(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*L+1),J(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0};return e.state=l,l.strm=e,l.wrap=n,l.gzhead=null,l.w_bits=s,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=o+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+B-1)/B),l.window=new r.Buf8(2*l.w_size),l.head=new r.Buf16(l.hash_size),l.prev=new r.Buf16(l.w_size),l.lit_bufsize=1<<o+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new r.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=a,l.method=i,ce(e)}s=[new le(0,0,0,0,function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(oe(e),0===e.lookahead&&t===h)return W;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var s=e.block_start+i;if((0===e.strstart||e.strstart>=s)&&(e.lookahead=e.strstart-s,e.strstart=s,te(e,!1),0===e.strm.avail_out))return W;if(e.strstart-e.block_start>=e.w_size-N&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):(e.strstart>e.block_start&&(te(e,!1),e.strm.avail_out),W)}),new le(4,4,8,4,ae),new le(4,5,16,8,ae),new le(4,6,32,32,ae),new le(4,4,16,16,ne),new le(8,16,32,32,ne),new le(8,16,128,128,ne),new le(8,32,128,256,ne),new le(32,128,258,1024,ne),new le(32,258,258,4096,ne)],i.deflateInit=function(e,t){return de(e,t,A,S,R,P)},i.deflateInit2=de,i.deflateReset=ce,i.deflateResetKeep=he,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?g:(e.state.gzhead=t,m):g},i.deflate=function(e,t){var i,r,a,l;if(!e||!e.state||t>p||t<0)return e?Z(e,g):g;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||r.status===$&&t!==u)return Z(e,0===e.avail_out?v:g);if(r.strm=e,i=r.last_flush,r.last_flush=t,r.status===O)if(2===r.wrap)e.adler=0,ie(r,31),ie(r,139),ie(r,8),r.gzhead?(ie(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),ie(r,255&r.gzhead.time),ie(r,r.gzhead.time>>8&255),ie(r,r.gzhead.time>>16&255),ie(r,r.gzhead.time>>24&255),ie(r,9===r.level?2:r.strategy>=M||r.level<2?4:0),ie(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(ie(r,255&r.gzhead.extra.length),ie(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=n(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=j):(ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,0),ie(r,9===r.level?2:r.strategy>=M||r.level<2?4:0),ie(r,K),r.status=H);else{var f=A+(r.w_bits-8<<4)<<8;f|=(r.strategy>=M||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(f|=V),f+=31-f%31,r.status=H,se(r,f),0!==r.strstart&&(se(r,e.adler>>>16),se(r,65535&e.adler)),e.adler=1}if(r.status===j)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending!==r.pending_buf_size));)ie(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=U)}else r.status=U;if(r.status===U)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,ie(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.gzindex=0,r.status=G)}else r.status=G;if(r.status===G)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),ee(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,ie(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.status=z)}else r.status=z;if(r.status===z&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&ee(e),r.pending+2<=r.pending_buf_size&&(ie(r,255&e.adler),ie(r,e.adler>>8&255),e.adler=0,r.status=H)):r.status=H),0!==r.pending){if(ee(e),0===e.avail_out)return r.last_flush=-1,m}else if(0===e.avail_in&&Q(t)<=Q(i)&&t!==u)return Z(e,v);if(r.status===$&&0!==e.avail_in)return Z(e,v);if(0!==e.avail_in||0!==r.lookahead||t!==h&&r.status!==$){var b=r.strategy===M?function(e,t){for(var i;;){if(0===e.lookahead&&(oe(e),0===e.lookahead)){if(t===h)return W;break}if(e.match_length=0,i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}(r,t):r.strategy===w?function(e,t){for(var i,s,r,a,n=e.window;;){if(e.lookahead<=F){if(oe(e),e.lookahead<=F&&t===h)return W;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=B&&e.strstart>0&&(s=n[r=e.strstart-1])===n[++r]&&s===n[++r]&&s===n[++r]){a=e.strstart+F;do{}while(s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&r<a);e.match_length=F-(a-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=B?(i=o._tr_tally(e,1,e.match_length-B),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(te(e,!1),0===e.strm.avail_out))return W}return e.insert=0,t===u?(te(e,!0),0===e.strm.avail_out?Y:q):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?W:X}(r,t):s[r.level].func(r,t);if(b!==Y&&b!==q||(r.status=$),b===W||b===Y)return 0===e.avail_out&&(r.last_flush=-1),m;if(b===X&&(t===c?o._tr_align(r):t!==p&&(o._tr_stored_block(r,0,0,!1),t===d&&(J(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),ee(e),0===e.avail_out))return r.last_flush=-1,m}return t!==u?m:r.wrap<=0?_:(2===r.wrap?(ie(r,255&e.adler),ie(r,e.adler>>8&255),ie(r,e.adler>>16&255),ie(r,e.adler>>24&255),ie(r,255&e.total_in),ie(r,e.total_in>>8&255),ie(r,e.total_in>>16&255),ie(r,e.total_in>>24&255)):(se(r,e.adler>>>16),se(r,65535&e.adler)),ee(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?m:_)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==O&&t!==j&&t!==U&&t!==G&&t!==z&&t!==H&&t!==$?Z(e,g):(e.state=null,t===H?Z(e,f):m):g},i.deflateSetDictionary=function(e,t){var i,s,o,n,l,h,c,d,u=t.length;if(!e||!e.state)return g;if(2===(n=(i=e.state).wrap)||1===n&&i.status!==O||i.lookahead)return g;for(1===n&&(e.adler=a(e.adler,t,u,0)),i.wrap=0,u>=i.w_size&&(0===n&&(J(i.head),i.strstart=0,i.block_start=0,i.insert=0),d=new r.Buf8(i.w_size),r.arraySet(d,t,u-i.w_size,i.w_size,0),t=d,u=i.w_size),l=e.avail_in,h=e.next_in,c=e.input,e.avail_in=u,e.next_in=0,e.input=t,oe(i);i.lookahead>=B;){s=i.strstart,o=i.lookahead-(B-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[s+B-1])&i.hash_mask,i.prev[s&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=s,s++}while(--o);i.strstart=s,i.lookahead=B-1,oe(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=B-1,i.match_available=0,e.next_in=h,e.input=c,e.avail_in=l,i.wrap=n,m},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":3,"./adler32":5,"./crc32":7,"./messages":13,"./trees":14}],9:[function(e,t,i){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],10:[function(e,t,i){t.exports=function(e,t){var i,s,r,o,a,n,l,h,c,d,u,p,m,_,g,f,v,b,y,M,w,x,P,E,A;i=e.state,s=e.next_in,E=e.input,r=s+(e.avail_in-5),o=e.next_out,A=e.output,a=o-(t-e.avail_out),n=o+(e.avail_out-257),l=i.dmax,h=i.wsize,c=i.whave,d=i.wnext,u=i.window,p=i.hold,m=i.bits,_=i.lencode,g=i.distcode,f=(1<<i.lenbits)-1,v=(1<<i.distbits)-1;e:do{m<15&&(p+=E[s++]<<m,m+=8,p+=E[s++]<<m,m+=8),b=_[p&f];t:for(;;){if(p>>>=y=b>>>24,m-=y,0===(y=b>>>16&255))A[o++]=65535&b;else{if(!(16&y)){if(0==(64&y)){b=_[(65535&b)+(p&(1<<y)-1)];continue t}if(32&y){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}M=65535&b,(y&=15)&&(m<y&&(p+=E[s++]<<m,m+=8),M+=p&(1<<y)-1,p>>>=y,m-=y),m<15&&(p+=E[s++]<<m,m+=8,p+=E[s++]<<m,m+=8),b=g[p&v];i:for(;;){if(p>>>=y=b>>>24,m-=y,!(16&(y=b>>>16&255))){if(0==(64&y)){b=g[(65535&b)+(p&(1<<y)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(w=65535&b,m<(y&=15)&&(p+=E[s++]<<m,(m+=8)<y&&(p+=E[s++]<<m,m+=8)),(w+=p&(1<<y)-1)>l){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=y,m-=y,w>(y=o-a)){if((y=w-y)>c&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(x=0,P=u,0===d){if(x+=h-y,y<M){M-=y;do{A[o++]=u[x++]}while(--y);x=o-w,P=A}}else if(d<y){if(x+=h+d-y,(y-=d)<M){M-=y;do{A[o++]=u[x++]}while(--y);if(x=0,d<M){M-=y=d;do{A[o++]=u[x++]}while(--y);x=o-w,P=A}}}else if(x+=d-y,y<M){M-=y;do{A[o++]=u[x++]}while(--y);x=o-w,P=A}for(;M>2;)A[o++]=P[x++],A[o++]=P[x++],A[o++]=P[x++],M-=3;M&&(A[o++]=P[x++],M>1&&(A[o++]=P[x++]))}else{x=o-w;do{A[o++]=A[x++],A[o++]=A[x++],A[o++]=A[x++],M-=3}while(M>2);M&&(A[o++]=A[x++],M>1&&(A[o++]=A[x++]))}break}}break}}while(s<r&&o<n);s-=M=m>>3,p&=(1<<(m-=M<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s<r?r-s+5:5-(s-r),e.avail_out=o<n?n-o+257:257-(o-n),i.hold=p,i.bits=m}},{}],11:[function(e,t,i){var s=e("../utils/common"),r=e("./adler32"),o=e("./crc32"),a=e("./inffast"),n=e("./inftrees"),l=0,h=1,c=2,d=4,u=5,p=6,m=0,_=1,g=2,f=-2,v=-3,b=-4,y=-5,M=8,w=1,x=2,P=3,E=4,A=5,C=6,S=7,R=8,L=9,D=10,k=11,T=12,I=13,B=14,F=15,N=16,V=17,O=18,j=19,U=20,G=21,z=22,H=23,$=24,W=25,X=26,Y=27,q=28,K=29,Z=30,Q=31,J=32,ee=852,te=592,ie=15;function se(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function re(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=w,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(ee),t.distcode=t.distdyn=new s.Buf32(te),t.sane=1,t.back=-1,m):f}function oe(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,re(e)):f}function ae(e,t){var i,s;return e&&e.state?(s=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?f:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,oe(e))):f}function ne(e,t){var i,r;return e?(r=new function(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0},e.state=r,r.window=null,(i=ae(e,t))!==m&&(e.state=null),i):f}var le,he,ce=!0;function de(e){if(ce){var t;for(le=new s.Buf32(512),he=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(n(h,e.lens,0,288,le,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;n(c,e.lens,0,32,he,0,e.work,{bits:5}),ce=!1}e.lencode=le,e.lenbits=9,e.distcode=he,e.distbits=5}function ue(e,t,i,r){var o,a=e.state;return null===a.window&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new s.Buf8(a.wsize)),r>=a.wsize?(s.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((o=a.wsize-a.wnext)>r&&(o=r),s.arraySet(a.window,t,i-r,o,a.wnext),(r-=o)?(s.arraySet(a.window,t,i-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=o,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=o))),0}i.inflateReset=oe,i.inflateReset2=ae,i.inflateResetKeep=re,i.inflateInit=function(e){return ne(e,ie)},i.inflateInit2=ne,i.inflate=function(e,t){var i,ee,te,ie,re,oe,ae,ne,le,he,ce,pe,me,_e,ge,fe,ve,be,ye,Me,we,xe,Pe,Ee,Ae=0,Ce=new s.Buf8(4),Se=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return f;(i=e.state).mode===T&&(i.mode=I),re=e.next_out,te=e.output,ae=e.avail_out,ie=e.next_in,ee=e.input,oe=e.avail_in,ne=i.hold,le=i.bits,he=oe,ce=ae,xe=m;e:for(;;)switch(i.mode){case w:if(0===i.wrap){i.mode=I;break}for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(2&i.wrap&&35615===ne){i.check=0,Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0),ne=0,le=0,i.mode=x;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&ne)<<8)+(ne>>8))%31){e.msg="incorrect header check",i.mode=Z;break}if((15&ne)!==M){e.msg="unknown compression method",i.mode=Z;break}if(le-=4,we=8+(15&(ne>>>=4)),0===i.wbits)i.wbits=we;else if(we>i.wbits){e.msg="invalid window size",i.mode=Z;break}i.dmax=1<<we,e.adler=i.check=1,i.mode=512&ne?D:T,ne=0,le=0;break;case x:for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(i.flags=ne,(255&i.flags)!==M){e.msg="unknown compression method",i.mode=Z;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=Z;break}i.head&&(i.head.text=ne>>8&1),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0,i.mode=P;case P:for(;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}i.head&&(i.head.time=ne),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,Ce[2]=ne>>>16&255,Ce[3]=ne>>>24&255,i.check=o(i.check,Ce,4,0)),ne=0,le=0,i.mode=E;case E:for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}i.head&&(i.head.xflags=255&ne,i.head.os=ne>>8),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0,i.mode=A;case A:if(1024&i.flags){for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}i.length=ne,i.head&&(i.head.extra_len=ne),512&i.flags&&(Ce[0]=255&ne,Ce[1]=ne>>>8&255,i.check=o(i.check,Ce,2,0)),ne=0,le=0}else i.head&&(i.head.extra=null);i.mode=C;case C:if(1024&i.flags&&((pe=i.length)>oe&&(pe=oe),pe&&(i.head&&(we=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),s.arraySet(i.head.extra,ee,ie,pe,we)),512&i.flags&&(i.check=o(i.check,ee,pe,ie)),oe-=pe,ie+=pe,i.length-=pe),i.length))break e;i.length=0,i.mode=S;case S:if(2048&i.flags){if(0===oe)break e;pe=0;do{we=ee[ie+pe++],i.head&&we&&i.length<65536&&(i.head.name+=String.fromCharCode(we))}while(we&&pe<oe);if(512&i.flags&&(i.check=o(i.check,ee,pe,ie)),oe-=pe,ie+=pe,we)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=R;case R:if(4096&i.flags){if(0===oe)break e;pe=0;do{we=ee[ie+pe++],i.head&&we&&i.length<65536&&(i.head.comment+=String.fromCharCode(we))}while(we&&pe<oe);if(512&i.flags&&(i.check=o(i.check,ee,pe,ie)),oe-=pe,ie+=pe,we)break e}else i.head&&(i.head.comment=null);i.mode=L;case L:if(512&i.flags){for(;le<16;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(ne!==(65535&i.check)){e.msg="header crc mismatch",i.mode=Z;break}ne=0,le=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=T;break;case D:for(;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}e.adler=i.check=se(ne),ne=0,le=0,i.mode=k;case k:if(0===i.havedict)return e.next_out=re,e.avail_out=ae,e.next_in=ie,e.avail_in=oe,i.hold=ne,i.bits=le,g;e.adler=i.check=1,i.mode=T;case T:if(t===u||t===p)break e;case I:if(i.last){ne>>>=7&le,le-=7&le,i.mode=Y;break}for(;le<3;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}switch(i.last=1&ne,le-=1,3&(ne>>>=1)){case 0:i.mode=B;break;case 1:if(de(i),i.mode=U,t===p){ne>>>=2,le-=2;break e}break;case 2:i.mode=V;break;case 3:e.msg="invalid block type",i.mode=Z}ne>>>=2,le-=2;break;case B:for(ne>>>=7&le,le-=7&le;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if((65535&ne)!=(ne>>>16^65535)){e.msg="invalid stored block lengths",i.mode=Z;break}if(i.length=65535&ne,ne=0,le=0,i.mode=F,t===p)break e;case F:i.mode=N;case N:if(pe=i.length){if(pe>oe&&(pe=oe),pe>ae&&(pe=ae),0===pe)break e;s.arraySet(te,ee,ie,pe,re),oe-=pe,ie+=pe,ae-=pe,re+=pe,i.length-=pe;break}i.mode=T;break;case V:for(;le<14;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(i.nlen=257+(31&ne),ne>>>=5,le-=5,i.ndist=1+(31&ne),ne>>>=5,le-=5,i.ncode=4+(15&ne),ne>>>=4,le-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Z;break}i.have=0,i.mode=O;case O:for(;i.have<i.ncode;){for(;le<3;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}i.lens[Se[i.have++]]=7&ne,ne>>>=3,le-=3}for(;i.have<19;)i.lens[Se[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,Pe={bits:i.lenbits},xe=n(l,i.lens,0,19,i.lencode,0,i.work,Pe),i.lenbits=Pe.bits,xe){e.msg="invalid code lengths set",i.mode=Z;break}i.have=0,i.mode=j;case j:for(;i.have<i.nlen+i.ndist;){for(;fe=(Ae=i.lencode[ne&(1<<i.lenbits)-1])>>>16&255,ve=65535&Ae,!((ge=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(ve<16)ne>>>=ge,le-=ge,i.lens[i.have++]=ve;else{if(16===ve){for(Ee=ge+2;le<Ee;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(ne>>>=ge,le-=ge,0===i.have){e.msg="invalid bit length repeat",i.mode=Z;break}we=i.lens[i.have-1],pe=3+(3&ne),ne>>>=2,le-=2}else if(17===ve){for(Ee=ge+3;le<Ee;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}le-=ge,we=0,pe=3+(7&(ne>>>=ge)),ne>>>=3,le-=3}else{for(Ee=ge+7;le<Ee;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}le-=ge,we=0,pe=11+(127&(ne>>>=ge)),ne>>>=7,le-=7}if(i.have+pe>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Z;break}for(;pe--;)i.lens[i.have++]=we}}if(i.mode===Z)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Z;break}if(i.lenbits=9,Pe={bits:i.lenbits},xe=n(h,i.lens,0,i.nlen,i.lencode,0,i.work,Pe),i.lenbits=Pe.bits,xe){e.msg="invalid literal/lengths set",i.mode=Z;break}if(i.distbits=6,i.distcode=i.distdyn,Pe={bits:i.distbits},xe=n(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,Pe),i.distbits=Pe.bits,xe){e.msg="invalid distances set",i.mode=Z;break}if(i.mode=U,t===p)break e;case U:i.mode=G;case G:if(oe>=6&&ae>=258){e.next_out=re,e.avail_out=ae,e.next_in=ie,e.avail_in=oe,i.hold=ne,i.bits=le,a(e,ce),re=e.next_out,te=e.output,ae=e.avail_out,ie=e.next_in,ee=e.input,oe=e.avail_in,ne=i.hold,le=i.bits,i.mode===T&&(i.back=-1);break}for(i.back=0;fe=(Ae=i.lencode[ne&(1<<i.lenbits)-1])>>>16&255,ve=65535&Ae,!((ge=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(fe&&0==(240&fe)){for(be=ge,ye=fe,Me=ve;fe=(Ae=i.lencode[Me+((ne&(1<<be+ye)-1)>>be)])>>>16&255,ve=65535&Ae,!(be+(ge=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}ne>>>=be,le-=be,i.back+=be}if(ne>>>=ge,le-=ge,i.back+=ge,i.length=ve,0===fe){i.mode=X;break}if(32&fe){i.back=-1,i.mode=T;break}if(64&fe){e.msg="invalid literal/length code",i.mode=Z;break}i.extra=15&fe,i.mode=z;case z:if(i.extra){for(Ee=i.extra;le<Ee;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}i.length+=ne&(1<<i.extra)-1,ne>>>=i.extra,le-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=H;case H:for(;fe=(Ae=i.distcode[ne&(1<<i.distbits)-1])>>>16&255,ve=65535&Ae,!((ge=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(0==(240&fe)){for(be=ge,ye=fe,Me=ve;fe=(Ae=i.distcode[Me+((ne&(1<<be+ye)-1)>>be)])>>>16&255,ve=65535&Ae,!(be+(ge=Ae>>>24)<=le);){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}ne>>>=be,le-=be,i.back+=be}if(ne>>>=ge,le-=ge,i.back+=ge,64&fe){e.msg="invalid distance code",i.mode=Z;break}i.offset=ve,i.extra=15&fe,i.mode=$;case $:if(i.extra){for(Ee=i.extra;le<Ee;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}i.offset+=ne&(1<<i.extra)-1,ne>>>=i.extra,le-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Z;break}i.mode=W;case W:if(0===ae)break e;if(pe=ce-ae,i.offset>pe){if((pe=i.offset-pe)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Z;break}pe>i.wnext?(pe-=i.wnext,me=i.wsize-pe):me=i.wnext-pe,pe>i.length&&(pe=i.length),_e=i.window}else _e=te,me=re-i.offset,pe=i.length;pe>ae&&(pe=ae),ae-=pe,i.length-=pe;do{te[re++]=_e[me++]}while(--pe);0===i.length&&(i.mode=G);break;case X:if(0===ae)break e;te[re++]=i.length,ae--,i.mode=G;break;case Y:if(i.wrap){for(;le<32;){if(0===oe)break e;oe--,ne|=ee[ie++]<<le,le+=8}if(ce-=ae,e.total_out+=ce,i.total+=ce,ce&&(e.adler=i.check=i.flags?o(i.check,te,ce,re-ce):r(i.check,te,ce,re-ce)),ce=ae,(i.flags?ne:se(ne))!==i.check){e.msg="incorrect data check",i.mode=Z;break}ne=0,le=0}i.mode=q;case q:if(i.wrap&&i.flags){for(;le<32;){if(0===oe)break e;oe--,ne+=ee[ie++]<<le,le+=8}if(ne!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=Z;break}ne=0,le=0}i.mode=K;case K:xe=_;break e;case Z:xe=v;break e;case Q:return b;case J:default:return f}return e.next_out=re,e.avail_out=ae,e.next_in=ie,e.avail_in=oe,i.hold=ne,i.bits=le,(i.wsize||ce!==e.avail_out&&i.mode<Z&&(i.mode<Y||t!==d))&&ue(e,e.output,e.next_out,ce-e.avail_out),he-=e.avail_in,ce-=e.avail_out,e.total_in+=he,e.total_out+=ce,i.total+=ce,i.wrap&&ce&&(e.adler=i.check=i.flags?o(i.check,te,ce,e.next_out-ce):r(i.check,te,ce,e.next_out-ce)),e.data_type=i.bits+(i.last?64:0)+(i.mode===T?128:0)+(i.mode===U||i.mode===F?256:0),(0===he&&0===ce||t===d)&&xe===m&&(xe=y),xe},i.inflateEnd=function(e){if(!e||!e.state)return f;var t=e.state;return t.window&&(t.window=null),e.state=null,m},i.inflateGetHeader=function(e,t){var i;return e&&e.state?0==(2&(i=e.state).wrap)?f:(i.head=t,t.done=!1,m):f},i.inflateSetDictionary=function(e,t){var i,s=t.length;return e&&e.state?0!==(i=e.state).wrap&&i.mode!==k?f:i.mode===k&&r(1,t,s,0)!==i.check?v:ue(e,t,s,s)?(i.mode=Q,b):(i.havedict=1,m):f},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":3,"./adler32":5,"./crc32":7,"./inffast":10,"./inftrees":12}],12:[function(e,t,i){var s=e("../utils/common"),r=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],a=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,i,l,h,c,d,u){var p,m,_,g,f,v,b,y,M,w=u.bits,x=0,P=0,E=0,A=0,C=0,S=0,R=0,L=0,D=0,k=0,T=null,I=0,B=new s.Buf16(16),F=new s.Buf16(16),N=null,V=0;for(x=0;x<=15;x++)B[x]=0;for(P=0;P<l;P++)B[t[i+P]]++;for(C=w,A=15;A>=1&&0===B[A];A--);if(C>A&&(C=A),0===A)return h[c++]=20971520,h[c++]=20971520,u.bits=1,0;for(E=1;E<A&&0===B[E];E++);for(C<E&&(C=E),L=1,x=1;x<=15;x++)if(L<<=1,(L-=B[x])<0)return-1;if(L>0&&(0===e||1!==A))return-1;for(F[1]=0,x=1;x<15;x++)F[x+1]=F[x]+B[x];for(P=0;P<l;P++)0!==t[i+P]&&(d[F[t[i+P]]++]=P);if(0===e?(T=N=d,v=19):1===e?(T=r,I-=257,N=o,V-=257,v=256):(T=a,N=n,v=-1),k=0,P=0,x=E,f=c,S=C,R=0,_=-1,g=(D=1<<C)-1,1===e&&D>852||2===e&&D>592)return 1;for(;;){b=x-R,d[P]<v?(y=0,M=d[P]):d[P]>v?(y=N[V+d[P]],M=T[I+d[P]]):(y=96,M=0),p=1<<x-R,E=m=1<<S;do{h[f+(k>>R)+(m-=p)]=b<<24|y<<16|M|0}while(0!==m);for(p=1<<x-1;k&p;)p>>=1;if(0!==p?(k&=p-1,k+=p):k=0,P++,0==--B[x]){if(x===A)break;x=t[i+d[P]]}if(x>C&&(k&g)!==_){for(0===R&&(R=C),f+=E,L=1<<(S=x-R);S+R<A&&!((L-=B[S+R])<=0);)S++,L<<=1;if(D+=1<<S,1===e&&D>852||2===e&&D>592)return 1;h[_=k&g]=C<<24|S<<16|f-c|0}}return 0!==k&&(h[f+k]=x-R<<24|64<<16|0),u.bits=C,0}},{"../utils/common":3}],13:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],14:[function(e,t,i){var s=e("../utils/common"),r=4,o=0,a=1,n=2;function l(e){for(var t=e.length;--t>=0;)e[t]=0}var h=0,c=1,d=2,u=29,p=256,m=p+1+u,_=30,g=19,f=2*m+1,v=15,b=16,y=7,M=256,w=16,x=17,P=18,E=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],A=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],C=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],R=new Array(2*(m+2));l(R);var L=new Array(2*_);l(L);var D=new Array(512);l(D);var k=new Array(256);l(k);var T=new Array(u);l(T);var I,B,F,N=new Array(_);function V(e,t,i,s,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=s,this.max_length=r,this.has_stree=e&&e.length}function O(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function j(e){return e<256?D[e]:D[256+(e>>>7)]}function U(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function G(e,t,i){e.bi_valid>b-i?(e.bi_buf|=t<<e.bi_valid&65535,U(e,e.bi_buf),e.bi_buf=t>>b-e.bi_valid,e.bi_valid+=i-b):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function z(e,t,i){G(e,i[2*t],i[2*t+1])}function H(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function $(e,t,i){var s,r,o=new Array(v+1),a=0;for(s=1;s<=v;s++)o[s]=a=a+i[s-1]<<1;for(r=0;r<=t;r++){var n=e[2*r+1];0!==n&&(e[2*r]=H(o[n]++,n))}}function W(e){var t;for(t=0;t<m;t++)e.dyn_ltree[2*t]=0;for(t=0;t<_;t++)e.dyn_dtree[2*t]=0;for(t=0;t<g;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*M]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function X(e){e.bi_valid>8?U(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Y(e,t,i,s){var r=2*t,o=2*i;return e[r]<e[o]||e[r]===e[o]&&s[t]<=s[i]}function q(e,t,i){for(var s=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&Y(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!Y(t,s,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=s}function K(e,t,i){var s,r,o,a,n=0;if(0!==e.last_lit)do{s=e.pending_buf[e.d_buf+2*n]<<8|e.pending_buf[e.d_buf+2*n+1],r=e.pending_buf[e.l_buf+n],n++,0===s?z(e,r,t):(z(e,(o=k[r])+p+1,t),0!==(a=E[o])&&G(e,r-=T[o],a),z(e,o=j(--s),i),0!==(a=A[o])&&G(e,s-=N[o],a))}while(n<e.last_lit);z(e,M,t)}function Z(e,t){var i,s,r,o=t.dyn_tree,a=t.stat_desc.static_tree,n=t.stat_desc.has_stree,l=t.stat_desc.elems,h=-1;for(e.heap_len=0,e.heap_max=f,i=0;i<l;i++)0!==o[2*i]?(e.heap[++e.heap_len]=h=i,e.depth[i]=0):o[2*i+1]=0;for(;e.heap_len<2;)o[2*(r=e.heap[++e.heap_len]=h<2?++h:0)]=1,e.depth[r]=0,e.opt_len--,n&&(e.static_len-=a[2*r+1]);for(t.max_code=h,i=e.heap_len>>1;i>=1;i--)q(e,o,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],q(e,o,1),s=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=s,o[2*r]=o[2*i]+o[2*s],e.depth[r]=(e.depth[i]>=e.depth[s]?e.depth[i]:e.depth[s])+1,o[2*i+1]=o[2*s+1]=r,e.heap[1]=r++,q(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,s,r,o,a,n,l=t.dyn_tree,h=t.max_code,c=t.stat_desc.static_tree,d=t.stat_desc.has_stree,u=t.stat_desc.extra_bits,p=t.stat_desc.extra_base,m=t.stat_desc.max_length,_=0;for(o=0;o<=v;o++)e.bl_count[o]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<f;i++)(o=l[2*l[2*(s=e.heap[i])+1]+1]+1)>m&&(o=m,_++),l[2*s+1]=o,s>h||(e.bl_count[o]++,a=0,s>=p&&(a=u[s-p]),n=l[2*s],e.opt_len+=n*(o+a),d&&(e.static_len+=n*(c[2*s+1]+a)));if(0!==_){do{for(o=m-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[m]--,_-=2}while(_>0);for(o=m;0!==o;o--)for(s=e.bl_count[o];0!==s;)(r=e.heap[--i])>h||(l[2*r+1]!==o&&(e.opt_len+=(o-l[2*r+1])*l[2*r],l[2*r+1]=o),s--)}}(e,t),$(o,h,e.bl_count)}function Q(e,t,i){var s,r,o=-1,a=t[1],n=0,l=7,h=4;for(0===a&&(l=138,h=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=a,a=t[2*(s+1)+1],++n<l&&r===a||(n<h?e.bl_tree[2*r]+=n:0!==r?(r!==o&&e.bl_tree[2*r]++,e.bl_tree[2*w]++):n<=10?e.bl_tree[2*x]++:e.bl_tree[2*P]++,n=0,o=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4))}function J(e,t,i){var s,r,o=-1,a=t[1],n=0,l=7,h=4;for(0===a&&(l=138,h=3),s=0;s<=i;s++)if(r=a,a=t[2*(s+1)+1],!(++n<l&&r===a)){if(n<h)do{z(e,r,e.bl_tree)}while(0!=--n);else 0!==r?(r!==o&&(z(e,r,e.bl_tree),n--),z(e,w,e.bl_tree),G(e,n-3,2)):n<=10?(z(e,x,e.bl_tree),G(e,n-3,3)):(z(e,P,e.bl_tree),G(e,n-11,7));n=0,o=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4)}}l(N);var ee=!1;function te(e,t,i,r){G(e,(h<<1)+(r?1:0),3),function(e,t,i,r){X(e),r&&(U(e,i),U(e,~i)),s.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}(e,t,i,!0)}i._tr_init=function(e){ee||(function(){var e,t,i,s,r,o=new Array(v+1);for(i=0,s=0;s<u-1;s++)for(T[s]=i,e=0;e<1<<E[s];e++)k[i++]=s;for(k[i-1]=s,r=0,s=0;s<16;s++)for(N[s]=r,e=0;e<1<<A[s];e++)D[r++]=s;for(r>>=7;s<_;s++)for(N[s]=r<<7,e=0;e<1<<A[s]-7;e++)D[256+r++]=s;for(t=0;t<=v;t++)o[t]=0;for(e=0;e<=143;)R[2*e+1]=8,e++,o[8]++;for(;e<=255;)R[2*e+1]=9,e++,o[9]++;for(;e<=279;)R[2*e+1]=7,e++,o[7]++;for(;e<=287;)R[2*e+1]=8,e++,o[8]++;for($(R,m+1,o),e=0;e<_;e++)L[2*e+1]=5,L[2*e]=H(e,5);I=new V(R,E,p+1,m,v),B=new V(L,A,0,_,v),F=new V(new Array(0),C,0,g,y)}(),ee=!0),e.l_desc=new O(e.dyn_ltree,I),e.d_desc=new O(e.dyn_dtree,B),e.bl_desc=new O(e.bl_tree,F),e.bi_buf=0,e.bi_valid=0,W(e)},i._tr_stored_block=te,i._tr_flush_block=function(e,t,i,s){var l,h,u=0;e.level>0?(e.strm.data_type===n&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return o;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return a;for(t=32;t<p;t++)if(0!==e.dyn_ltree[2*t])return a;return o}(e)),Z(e,e.l_desc),Z(e,e.d_desc),u=function(e){var t;for(Q(e,e.dyn_ltree,e.l_desc.max_code),Q(e,e.dyn_dtree,e.d_desc.max_code),Z(e,e.bl_desc),t=g-1;t>=3&&0===e.bl_tree[2*S[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),l=e.opt_len+3+7>>>3,(h=e.static_len+3+7>>>3)<=l&&(l=h)):l=h=i+5,i+4<=l&&-1!==t?te(e,t,i,s):e.strategy===r||h===l?(G(e,(c<<1)+(s?1:0),3),K(e,R,L)):(G(e,(d<<1)+(s?1:0),3),function(e,t,i,s){var r;for(G(e,t-257,5),G(e,i-1,5),G(e,s-4,4),r=0;r<s;r++)G(e,e.bl_tree[2*S[r]+1],3);J(e,e.dyn_ltree,t-1),J(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,u+1),K(e,e.dyn_ltree,e.dyn_dtree)),W(e),s&&X(e)},i._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(k[i]+p+1)]++,e.dyn_dtree[2*j(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){G(e,c<<1,3),z(e,M,R),function(e){16===e.bi_valid?(U(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":3}],15:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/":[function(e,t,i){var s={};(0,e("./lib/utils/common").assign)(s,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=s},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")});var p=Object.freeze({__proto__:null});let pako=window.pako||p;pako.inflate||(pako=pako.default);const decompressColor=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function extract(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11]}}function inflate(e){return{positions:new Uint16Array(pako.inflate(e.positions).buffer),normals:new Int8Array(pako.inflate(e.normals).buffer),indices:new Uint32Array(pako.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(pako.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(pako.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(pako.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(pako.inflate(e.meshColors).buffer),entityIDs:pako.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(pako.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(pako.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(pako.inflate(e.positionsDecodeMatrix).buffer)}}function load(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,u=JSON.parse(i.entityIDs),p=i.entityMeshes,m=i.entityIsObjects,_=l.length,g=p.length;for(let f=0;f<g;f++){const v=u[f],b=e.metaScene.metaObjects[v],y={},M={};if(b){if(t.excludeTypesMap&&b.type&&t.excludeTypesMap[b.type])continue;if(t.includeTypesMap&&b.type&&!t.includeTypesMap[b.type])continue;const e=t.objectDefaults?t.objectDefaults[b.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(y.visible=!1),!1===e.pickable&&(y.pickable=!1),e.colorize&&(M.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(M.opacity=e.opacity))}else if(t.excludeUnclassifiedObjects)continue;const w=f===g-1,x=[];for(let e=p[f],t=w?p.length:p[f+1];e<t;e++){const t=e===_-1,u=v+".mesh."+e,p=decompressColor(d.subarray(4*e,4*e+3)),m=d[4*e+3]/255;s.createMesh(utils.apply(M,{id:u,primitive:"triangles",positions:r.subarray(l[e],t?r.length:l[e+1]),normals:o.subarray(l[e],t?r.length:l[e+1]),indices:a.subarray(h[e],t?a.length:h[e+1]),edgeIndices:n.subarray(c[e],t?n.length:c[e+1]),positionsDecodeMatrix:i.positionsDecodeMatrix,color:p,opacity:m})),x.push(u)}s.createEntity(utils.apply(y,{id:v,isObject:1===m[f],meshIds:x}))}}const ParserV1={version:1,parse:function(e,t,i,s){load(e,t,inflate(extract(i)),s)}};let pako$1=window.pako||p;function extract$1(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11],entityMeshIds:e[12],entityMatrices:e[13],entityUsesInstancing:e[14]}}function inflate$1(e){return{positions:new Uint16Array(pako$1.inflate(e.positions).buffer),normals:new Int8Array(pako$1.inflate(e.normals).buffer),indices:new Uint32Array(pako$1.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$1.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(pako$1.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(pako$1.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(pako$1.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(pako$1.inflate(e.meshColors).buffer),entityIDs:pako$1.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(pako$1.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(pako$1.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(pako$1.inflate(e.positionsDecodeMatrix).buffer),entityMeshIds:new Uint32Array(pako$1.inflate(e.entityMeshIds).buffer),entityMatrices:new Float32Array(pako$1.inflate(e.entityMatrices).buffer),entityUsesInstancing:new Uint8Array(pako$1.inflate(e.entityUsesInstancing).buffer)}}pako$1.inflate||(pako$1=pako$1.default);const decompressColor$1=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$1(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,u=JSON.parse(i.entityIDs),p=i.entityMeshes,m=i.entityIsObjects,_=i.entityMeshIds,g=i.entityMatrices,f=i.entityUsesInstancing,v=l.length,b=p.length,y={};for(let M=0;M<b;M++){const w=u[M],x=e.metaScene.metaObjects[w],P={},E={},A=g.subarray(16*M,16*M+16);if(x){if(t.excludeTypesMap&&x.type&&t.excludeTypesMap[x.type])continue;if(t.includeTypesMap&&x.type&&!t.includeTypesMap[x.type])continue;const e=t.objectDefaults?t.objectDefaults[x.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(P.visible=!1),!1===e.pickable&&(P.pickable=!1),e.colorize&&(E.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(E.opacity=e.opacity))}else if(t.excludeUnclassifiedObjects)continue;const C=M===b-1,S=[];for(let e=p[M],t=C?_.length:p[M+1];e<t;e++){const t=_[e],u=t===v-1,p=w+".mesh."+t,m=decompressColor$1(d.subarray(4*t,4*t+3)),g=d[4*t+3]/255,b=r.subarray(l[t],u?r.length:l[t+1]),x=o.subarray(l[t],u?r.length:l[t+1]),P=a.subarray(h[t],u?a.length:h[t+1]),C=n.subarray(c[t],u?n.length:c[t+1]);if(1===f[M]){const e="geometry."+t;e in y||(s.createGeometry({id:e,positions:b,normals:x,indices:P,edgeIndices:C,primitive:"triangles",positionsDecodeMatrix:i.positionsDecodeMatrix}),y[e]=!0),s.createMesh(utils.apply(E,{id:p,color:m,opacity:g,matrix:A,geometryId:e})),S.push(p)}else s.createMesh(utils.apply(E,{id:p,primitive:"triangles",positions:b,normals:x,indices:P,edgeIndices:C,positionsDecodeMatrix:i.positionsDecodeMatrix,color:m,opacity:g})),S.push(p)}S.length&&s.createEntity(utils.apply(P,{id:w,isObject:1===m[M],meshIds:S}))}}const ParserV2={version:2,parse:function(e,t,i,s){load$1(e,t,inflate$1(extract$1(i)),s)}};let pako$2=window.pako||p;function extract$2(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],instancedPositionsDecodeMatrix:e[11],batchedPositionsDecodeMatrix:e[12],entityMeshIds:e[13],entityMatrices:e[14],entityUsesInstancing:e[15]}}function inflate$2(e){return{positions:new Uint16Array(pako$2.inflate(e.positions).buffer),normals:new Int8Array(pako$2.inflate(e.normals).buffer),indices:new Uint32Array(pako$2.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$2.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(pako$2.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(pako$2.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(pako$2.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(pako$2.inflate(e.meshColors).buffer),entityIDs:pako$2.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(pako$2.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(pako$2.inflate(e.entityIsObjects).buffer),instancedPositionsDecodeMatrix:new Float32Array(pako$2.inflate(e.instancedPositionsDecodeMatrix).buffer),batchedPositionsDecodeMatrix:new Float32Array(pako$2.inflate(e.batchedPositionsDecodeMatrix).buffer),entityMeshIds:new Uint32Array(pako$2.inflate(e.entityMeshIds).buffer),entityMatrices:new Float32Array(pako$2.inflate(e.entityMatrices).buffer),entityUsesInstancing:new Uint8Array(pako$2.inflate(e.entityUsesInstancing).buffer)}}pako$2.inflate||(pako$2=pako$2.default);const decompressColor$2=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$2(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,u=JSON.parse(i.entityIDs),p=i.entityMeshes,m=i.entityIsObjects,_=i.entityMeshIds,g=i.entityMatrices,f=i.entityUsesInstancing,v=l.length,b=p.length,y={};for(let C=0;C<b;C++){const S=u[C],R=e.metaScene.metaObjects[S],L={},D={},k=g.subarray(16*C,16*C+16);if(R){if(t.excludeTypesMap&&R.type&&t.excludeTypesMap[R.type])continue;if(t.includeTypesMap&&R.type&&!t.includeTypesMap[R.type])continue;const e=t.objectDefaults?t.objectDefaults[R.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(L.visible=!1),!1===e.pickable&&(L.pickable=!1),e.colorize&&(D.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(D.opacity=e.opacity))}else if(t.excludeUnclassifiedObjects)continue;const T=C===b-1,I=[];for(let e=p[C],t=T?_.length:p[C+1];e<t;e++){var M=_[e];const t=M===v-1,u=S+".mesh."+M,p=decompressColor$2(d.subarray(4*M,4*M+3)),m=d[4*M+3]/255;var w=r.subarray(l[M],t?r.length:l[M+1]),x=o.subarray(l[M],t?r.length:l[M+1]),P=a.subarray(h[M],t?a.length:h[M+1]),E=n.subarray(c[M],t?n.length:c[M+1]);if(1===f[C]){var A="geometry."+M;A in y||(s.createGeometry({id:A,positions:w,normals:x,indices:P,edgeIndices:E,primitive:"triangles",positionsDecodeMatrix:i.instancedPositionsDecodeMatrix}),y[A]=!0),s.createMesh(utils.apply(D,{id:u,color:p,opacity:m,matrix:k,geometryId:A})),I.push(u)}else s.createMesh(utils.apply(D,{id:u,primitive:"triangles",positions:w,normals:x,indices:P,edgeIndices:E,positionsDecodeMatrix:i.batchedPositionsDecodeMatrix,color:p,opacity:m})),I.push(u)}I.length&&s.createEntity(utils.apply(L,{id:S,isObject:1===m[C],meshIds:I}))}}const ParserV3={version:3,parse:function(e,t,i,s){load$2(e,t,inflate$2(extract$2(i)),s)}};let pako$3=window.pako||p;function extract$3(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],decodeMatrices:e[4],matrices:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveDecodeMatricesPortion:e[9],eachPrimitiveColor:e[10],primitiveInstances:e[11],eachEntityId:e[12],eachEntityPrimitiveInstancesPortion:e[13],eachEntityMatricesPortion:e[14],eachEntityMatrix:e[15]}}function inflate$3(e){return{positions:new Uint16Array(pako$3.inflate(e.positions).buffer),normals:new Int8Array(pako$3.inflate(e.normals).buffer),indices:new Uint32Array(pako$3.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$3.inflate(e.edgeIndices).buffer),decodeMatrices:new Float32Array(pako$3.inflate(e.decodeMatrices).buffer),matrices:new Float32Array(pako$3.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(pako$3.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(pako$3.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(pako$3.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveDecodeMatricesPortion:new Uint32Array(pako$3.inflate(e.eachPrimitiveDecodeMatricesPortion).buffer),eachPrimitiveColor:new Uint8Array(pako$3.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(pako$3.inflate(e.primitiveInstances).buffer),eachEntityId:pako$3.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(pako$3.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(pako$3.inflate(e.eachEntityMatricesPortion).buffer)}}pako$3.inflate||(pako$3=pako$3.default);const decompressColor$3=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$3(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.decodeMatrices,h=i.matrices,c=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,u=i.eachPrimitiveEdgeIndicesPortion,p=i.eachPrimitiveDecodeMatricesPortion,m=i.eachPrimitiveColor,_=i.primitiveInstances,g=JSON.parse(i.eachEntityId),f=i.eachEntityPrimitiveInstancesPortion,v=i.eachEntityMatricesPortion,b=c.length,y=_.length,M=new Uint8Array(b),w=new Uint32Array(b),x=g.length;for(let e=0;e<b;e++)w[e]=e;w.sort((e,t)=>p[e]<p[t]?-1:p[e]>p[t]?1:0);for(let e=0;e<y;e++){M[_[e]]++}const P={};for(let e=0;e<x;e++){const t=x-1,i=e===t,s=f[e],r=i?f[t]:f[e+1];for(let t=s;t<r;t++){const i=_[t];M[i]>1||(P[i]=e)}}for(let e=0;e<b;e++){const t=w[e],i=t===b-1,h=M[t]>1,_=decompressColor$3(m.subarray(4*t,4*t+3)),f=m[4*t+3]/255,v=r.subarray(c[t],i?r.length:c[t+1]),y=o.subarray(c[t],i?o.length:c[t+1]),x=a.subarray(d[t],i?a.length:d[t+1]),A=n.subarray(u[t],i?n.length:u[t+1]),C=l.subarray(p[t],p[t]+16);if(h){var E="geometry"+t;s.createGeometry({id:E,primitive:"triangles",positions:v,normals:y,indices:x,edgeIndices:A,positionsDecodeMatrix:C})}else{const e=t,i=(g[P[t]],{});s.createMesh(utils.apply(i,{id:e,primitive:"triangles",positions:v,normals:y,indices:x,edgeIndices:A,positionsDecodeMatrix:C,color:_,opacity:f}))}}let A=0;for(let e=0;e<x;e++){const t=x-1,i=e===t,r=g[e],o=f[e],a=i?f[t]:f[e+1],n=[];for(let t=o;t<a;t++){const i=_[t];if(M[i]>1){const t={},r="instance."+A++,o="geometry"+i,a=16*v[e],l=h.subarray(a,a+16);s.createMesh(utils.apply(t,{id:r,geometryId:o,matrix:l})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(utils.apply(e,{id:r,isObject:!0,meshIds:n}))}}}const ParserV4={version:4,parse:function(e,t,i,s){load$3(e,t,inflate$3(extract$3(i)),s)}};let pako$4=window.pako||p;function extract$4(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],eachPrimitivePositionsAndNormalsPortion:e[5],eachPrimitiveIndicesPortion:e[6],eachPrimitiveEdgeIndicesPortion:e[7],eachPrimitiveColor:e[8],primitiveInstances:e[9],eachEntityId:e[10],eachEntityPrimitiveInstancesPortion:e[11],eachEntityMatricesPortion:e[12]}}function inflate$4(e){return{positions:new Float32Array(pako$4.inflate(e.positions).buffer),normals:new Int8Array(pako$4.inflate(e.normals).buffer),indices:new Uint32Array(pako$4.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pako$4.inflate(e.edgeIndices).buffer),matrices:new Float32Array(pako$4.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(pako$4.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(pako$4.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(pako$4.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(pako$4.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(pako$4.inflate(e.primitiveInstances).buffer),eachEntityId:pako$4.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(pako$4.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(pako$4.inflate(e.eachEntityMatricesPortion).buffer)}}pako$4.inflate||(pako$4=pako$4.default);const decompressColor$4=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function load$4(e,t,i,s){s.positionsCompression="disabled",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,c=i.eachPrimitiveIndicesPortion,d=i.eachPrimitiveEdgeIndicesPortion,u=i.eachPrimitiveColor,p=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,g=i.eachEntityMatricesPortion,f=h.length,v=p.length,b=new Uint8Array(f),y=m.length;for(let e=0;e<v;e++){b[p[e]]++}const M={};for(let e=0;e<y;e++){const t=y-1,i=e===t,s=_[e],r=i?_[t]:_[e+1];for(let t=s;t<r;t++){const i=p[t];b[i]>1||(M[i]=e)}}for(let e=0;e<f;e++){const t=e===f-1,i=b[e]>1,l=decompressColor$4(u.subarray(4*e,4*e+3)),p=u[4*e+3]/255,_=r.subarray(h[e],t?r.length:h[e+1]),g=o.subarray(h[e],t?o.length:h[e+1]),v=a.subarray(c[e],t?a.length:c[e+1]),y=n.subarray(d[e],t?n.length:d[e+1]);if(i){var w="geometry"+e;s.createGeometry({id:w,primitive:"triangles",positions:_,normals:g,indices:v,edgeIndices:y})}else{const t=e,i=(m[M[e]],{});s.createMesh(utils.apply(i,{id:t,primitive:"triangles",positions:_,normals:g,indices:v,edgeIndices:y,color:l,opacity:p}))}}let x=0;for(let e=0;e<y;e++){const t=y-1,i=e===t,r=m[e],o=_[e],a=i?_[t]:_[e+1],n=[];for(let t=o;t<a;t++){const i=p[t];if(b[i]>1){const t={},r="instance."+x++,o="geometry"+i,a=16*g[e],h=l.subarray(a,a+16);s.createMesh(utils.apply(t,{id:r,geometryId:o,matrix:h})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(utils.apply(e,{id:r,isObject:!0,meshIds:n}))}}}const ParserV5={version:5,parse:function(e,t,i,s){load$4(e,t,inflate$4(extract$4(i)),s)}},parsers={};parsers[ParserV1.version]=ParserV1,parsers[ParserV2.version]=ParserV2,parsers[ParserV3.version]=ParserV3,parsers[ParserV4.version]=ParserV4,parsers[ParserV5.version]=ParserV5;class XKTLoaderPlugin extends Plugin{constructor(e,t={}){super("XKTLoader",e,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults,this.includeTypes=t.includeTypes,this.excludeTypes=t.excludeTypes,this.excludeUnclassifiedObjects=t.excludeUnclassifiedObjects}get supportedVersions(){return Object.keys(parsers)}set dataSource(e){this._dataSource=e||new XKTDefaultDataSource}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||IFCObjectDefaults}get objectDefaults(){return this._objectDefaults}set includeTypes(e){this._includeTypes=e}get includeTypes(){return this._includeTypes}set excludeTypes(e){this._excludeTypes=e}get excludeTypes(){return this._excludeTypes}set excludeUnclassifiedObjects(e){this._excludeUnclassifiedObjects=!!e}get excludeUnclassifiedObjects(){return this._excludeUnclassifiedObjects}load(e={}){e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);const t=new PerformanceModel(this.viewer.scene,utils.apply(e,{isModel:!0})),i=t.id;if(!e.src&&!e.xkt)return this.error("load() param expected: src or xkt"),t;const s={};if(e.metaModelSrc||e.metaModelData){const r=e.includeTypes||this._includeTypes,o=e.excludeTypes||this._excludeTypes,a=e.objectDefaults||this._objectDefaults;if(r){s.includeTypesMap={};for(let e=0,t=r.length;e<t;e++)s.includeTypesMap[r[e]]=!0}if(o){s.excludeTypesMap={};for(let e=0,t=o.length;e<t;e++)s.excludeTypesMap[o[e]]=!0}a&&(s.objectDefaults=a),s.excludeUnclassifiedObjects=void 0!==e.excludeUnclassifiedObjects?!!e.excludeUnclassifiedObjects:this._excludeUnclassifiedObjects;const n=a=>{this.viewer.metaScene.createMetaModel(i,a,{includeTypes:r,excludeTypes:o}),this.viewer.scene.canvas.spinner.processes--,e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t)};if(e.metaModelSrc){const t=e.metaModelSrc;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getMetaModel(t,e=>{this.viewer.scene.canvas.spinner.processes--,n(e)},e=>{this.error(`load(): Failed to load model metadata for model '${i} from  '${t}' - ${e}`),this.viewer.scene.canvas.spinner.processes--})}else e.metaModelData&&n(e.metaModelData)}else e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t);return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getXKT(t.src,e=>{this._parseModel(e,t,i,s),r.processes--},e=>{r.processes--,this.error(e),s.fire("error",e)})}_parseModel(e,t,i,s){const r=new DataView(e),o=new Uint8Array(e),a=r.getUint32(0,!0),n=parsers[a];if(!n)return void this.error("Unsupported .XKT file version: "+a+" - this XKTLoaderPlugin supports versions "+Object.keys(parsers));this.log("Loading .xkt V"+a);const l=r.getUint32(4,!0),h=[];let c=4*(l+2);for(let e=0;e<l;e++){const t=r.getUint32(4*(e+2),!0);h.push(o.subarray(c,c+t)),c+=t}n.parse(this.viewer,i,h,s),s.finalize(),s.scene.once("tick",()=>{s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1)})}}const ModelIFCObjectColors={IfcSpace:{opacity:.3},IfcWindow:{opacity:.4},IfcOpeningElement:{opacity:.3},IfcPlate:{opacity:.3}},ViewerIFCObjectColors={IfcRoof:{colorize:[.837255,.203922,.270588],priority:0},IfcSlab:{colorize:[.637255,.603922,.670588],priority:0},IfcWall:{colorize:[.537255,.337255,.237255],priority:0},IfcWallStandardCase:{colorize:[.537255,.337255,.237255],priority:0},IfcCovering:{colorize:[.8470588235,.427450980392,0],priority:0},IfcDoor:{colorize:[.637255,.603922,.670588],priority:1},IfcStair:{colorize:[.637255,.603922,.670588],priority:2},IfcStairFlight:{colorize:[.637255,.603922,.670588],priority:2},IfcProxy:{colorize:[.137255,.403922,.870588],priority:2},IfcRamp:{colorize:[.8470588235,.427450980392,0],priority:2},IfcColumn:{colorize:[.137255,.403922,.870588],priority:3},IfcBeam:{colorize:[.137255,.403922,.870588],priority:3},IfcCurtainWall:{colorize:[.137255,.403922,.870588],priority:3},IfcPlate:{colorize:[.8470588235,.427450980392,0,.5],opacity:.5,priority:3},IfcTransportElement:{colorize:[.8470588235,.427450980392,0],priority:3},IfcFooting:{colorize:[.8470588235,.427450980392,0],priority:3},IfcRailing:{colorize:[.137255,.403922,.870588],priority:4},IfcFurnishingElement:{colorize:[.137255,.403922,.870588],priority:4},IfcFurniture:{colorize:[.8470588235,.427450980392,0],priority:4},IfcSystemFurnitureElement:{colorize:[.8470588235,.427450980392,0],priority:4},IfcFlowSegment:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowitting:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowTerminal:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowController:{colorize:[.8470588235,.427450980392,0],priority:5},IfcFlowFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctSegment:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDistributionFlowElement:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcLightFixture:{colorize:[.8470588235,.8470588235,.870588],priority:5},IfcAirTerminal:{colorize:[.8470588235,.427450980392,0],priority:6},IfcOpeningElement:{colorize:[.137255,.403922,.870588],opacity:.3,priority:6},IfcSpace:{colorize:[.137255,.403922,.870588],opacity:.5,priority:6},IfcWindow:{colorize:[.137255,.403922,.870588],opacity:.4,priority:6},IfcBuildingElementProxy:{colorize:[.5,.5,.5]},IfcSite:{colorize:[.137255,.403922,.870588]},IfcMember:{colorize:[.8470588235,.427450980392,0]},DEFAULT:{colorize:[.5,.5,.5],priority:10}};class ModelsContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"Load",getEnabled:function(e){return!e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.loadModel(e.modelId)}},{title:"Unload",getEnabled:function(e){return e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.unloadModel(e.modelId)}},{title:"Load All",getEnabled:function(e){const t=e.bimViewer,i=t.getModelIds();return t.getLoadedModelIds().length<i.length},doAction:function(e){e.bimViewer.loadAllModels()}},{title:"Unload All",getEnabled:function(e){return e.bimViewer.getLoadedModelIds().length>0},doAction:function(e){e.bimViewer.unloadAllModels()}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}const tempVec3$3=math.vec3();class ModelsExplorer extends Controller{constructor(e,t){if(super(e,t),!t.modelsTabElement)throw"Missing config: modelsTabElement";if(!t.unloadModelsButtonElement)throw"Missing config: unloadModelsButtonElement";if(!t.modelsElement)throw"Missing config: modelsElement";if(this._modelsTabElement=t.modelsTabElement,this._unloadModelsButtonElement=t.unloadModelsButtonElement,this._modelsElement=t.modelsElement,this._modelsTabButtonElement=this._modelsTabElement.querySelector(".xeokit-tab-btn"),!this._modelsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";this._xktLoader=new XKTLoaderPlugin(this.viewer,{objectDefaults:ModelIFCObjectColors}),this._modelsContextMenu=new ModelsContextMenu,this._modelsInfo={},this._numModelsLoaded=0,this._projectId=null}loadProject(e,t,i){this.server.getProject(e,i=>{this.unloadProject(),this._projectId=e,this._modelsInfo={},this._parseProject(i,t)},e=>{this.error(e),i&&i(e)})}_parseProject(e,t){this._buildModelsMenu(e),this._parseViewerConfigs(e),this._parseViewerContent(e,()=>{this._parseViewerState(e,()=>{t()})})}_buildModelsMenu(e){var t="";const i=e.models||[];this._modelsInfo={};for(let e=0,s=i.length;e<s;e++){const s=i[e];this._modelsInfo[s.id]=s,t+="<div class='xeokit-form-check'>",t+="<input id='"+s.id+"' type='checkbox' value=''><span id='span-"+s.id+"' class='disabled'>"+s.name+"</span>",t+="</div>"}this._modelsElement.innerHTML=t;for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.id,r=document.getElementById(""+s),o=document.getElementById("span-"+s);r.addEventListener("click",()=>{r.checked?this.loadModel(s):this.unloadModel(t.id)}),o.addEventListener("click",()=>{!!this.viewer.scene.models[s]?this.unloadModel(t.id):this.loadModel(s)}),o.oncontextmenu=(e=>{this._modelsContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,modelId:s},this._modelsContextMenu.show(e.pageX,e.pageY),e.preventDefault()})}}_parseViewerConfigs(e){const t=e.viewerConfigs;t&&this.bimViewer.setConfigs(t)}_parseViewerContent(e,t){const i=e.viewerContent;i?this._parseModelsLoaded(i,()=>{t()}):t()}_parseModelsLoaded(e,t){const i=e.modelsLoaded;i&&0!==i.length?this._loadNextModel(i.slice(0),t):t()}_loadNextModel(e,t){if(0===e.length)return void t();const i=e.pop();this.loadModel(i,()=>{this._loadNextModel(e,t)},()=>{this._loadNextModel(e,t)})}_parseViewerState(e,t){const i=e.viewerState;i?this.bimViewer.setViewerState(i,t):t()}unloadProject(){if(!this._projectId)return;const e=this.viewer.scene.models;for(var t in e)if(e.hasOwnProperty(t)){e[t].destroy()}this._modelsElement.innerHTML="",this._numModelsLoaded=0,this._unloadModelsButtonElement.classList.add("disabled");const i=this._projectId;this._projectId=null,this.fire("projectUnloaded",{projectId:i})}getLoadedProjectId(){return this._projectId}getModelIds(){return Object.keys(this._modelsInfo)}loadModel(e,t,i){if(!this._projectId){const e="No project currently loaded";return this.error(e),void(i&&i(e))}const s=this._modelsInfo[e];if(!s){const e="Model not in currently loaded project";return this.error(e),void(i&&i(e))}this.bimViewer._busyModal.show("Loading: "+s.name),this.server.getMetadata(this._projectId,e,r=>{this.server.getGeometry(this._projectId,e,i=>{const o="model"===(s.objectColorSource||this.bimViewer.getObjectColorSource())?ModelIFCObjectColors:ViewerIFCObjectColors;this._xktLoader.load({id:e,metaModelData:r,xkt:i,objectDefaults:o,excludeUnclassifiedObjects:!0,position:s.position,scale:s.scale,rotation:s.rotation,matrix:s.matrix,edges:!1!==s.edges,saoEnabled:s.saoEnabled}).on("loaded",()=>{document.getElementById(""+e).checked=!0;const i=this.viewer.scene,s=i.getAABB(i.visibleObjectIds);this._numModelsLoaded++,this._unloadModelsButtonElement.classList.remove("disabled"),1===this._numModelsLoaded?(this.viewer.cameraFlight.jumpTo({aabb:s}),this.viewer.cameraControl.pivotPos=math.getAABB3Center(s,tempVec3$3),this.fire("modelLoaded",e),this.bimViewer._busyModal.hide(),t&&t()):(this.fire("modelLoaded",e),this.bimViewer._busyModal.hide(),t&&t())})},e=>{this.bimViewer._busyModal.hide(),this.error(e),i&&i(e)})},e=>{this.bimViewer._busyModal.hide(),this.error(e),i&&i(e)})}unloadModel(e){const t=this.viewer.scene.models[e];if(!t)return void this.error("Model not loaded: "+e);t.destroy(),document.getElementById(""+e).checked=!1;document.getElementById("span-"+e);this._numModelsLoaded--,this._numModelsLoaded>0?this._unloadModelsButtonElement.classList.remove("disabled"):this._unloadModelsButtonElement.classList.add("disabled")}unloadAllModels(){const e=this.viewer.scene.models,t=Object.keys(e);for(var i=0,s=t.length;i<s;i++){const e=t[i];this.unloadModel(e)}}getNumModelsLoaded(){return this._numModelsLoaded}_getLoadedModelIds(){return Object.keys(this.viewer.scene.models)}isModelLoaded(e){return!!this.viewer.scene.models[e]}getModelsInfo(){return this._modelsInfo}getModelInfo(e){return this._modelsInfo[e]}setEnabled(e){e?(this._modelsTabButtonElement.classList.remove("disabled"),this._unloadModelsButtonElement.classList.remove("disabled")):(this._modelsTabButtonElement.classList.add("disabled"),this._unloadModelsButtonElement.classList.add("disabled"))}destroy(){super.destroy(),this._xktLoader.destroy()}}const idMap$1=new Map;class ModelTreeView{constructor(e,t,i,s,r){if(!r.containerElement)throw"Config expected: containerElement";const o=s.rootMetaObject;o&&(this._id=idMap$1.addItem(),this._baseId=""+this._id,this._viewer=e,this._metaModel=i,this._treeViewPlugin=t,this._rootMetaObject=o,this._containerElement=r.containerElement,this._rootElement=null,this._muteSceneEvents=!1,this._muteTreeEvents=!1,this._rootNodes=[],this._objectNodes={},this._rootName=r.rootName,this._sortNodes=r.sortNodes,this._pruneEmptyNodes=r.pruneEmptyNodes,this._showListItemElementId=null,this._containerElement.oncontextmenu=(e=>{e.preventDefault()}),this._onObjectVisibility=this._viewer.scene.on("objectVisibility",e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;const s=e.visible;if(!(s!==i.checked))return;this._muteTreeEvents=!0,i.checked=s,s?i.numVisibleEntities++:i.numVisibleEntities--;const r=document.getElementById(i.nodeId);r&&(r.checked=s);let o=i.parent;for(;o;){o.checked=s,s?o.numVisibleEntities++:o.numVisibleEntities--;const e=document.getElementById(o.nodeId);if(e){const t=o.numVisibleEntities>0;t!==e.checked&&(e.checked=t)}o=o.parent}this._muteTreeEvents=!1}),this.switchExpandHandler=(e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._expandSwitchElement(t)}),this.switchCollapseHandler=(e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._collapseSwitchElement(t)}),this._checkboxChangeHandler=(e=>{if(this._muteTreeEvents)return;this._muteSceneEvents=!0;const t=e.target,i=t.checked,s=t.id,r=this._nodeToObjectID(s),o=this._objectNodes[r],a=this._viewer.scene.objects;let n=0;this._withNodeTree(o,e=>{const t=e.objectId,s=e.nodeId,r=a[t],o=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,o&&i!==e.checked&&n++,e.checked=i;const l=document.getElementById(s);l&&(l.checked=i),r&&(r.visible=i)});let l=o.parent;for(;l;){l.checked=i;const e=document.getElementById(l.nodeId);i?l.numVisibleEntities+=n:l.numVisibleEntities-=n;const t=l.numVisibleEntities>0;t!==e.checked&&(e.checked=t),l=l.parent}this._muteSceneEvents=!1}),this._hierarchy=r.hierarchy||"containment",this._autoExpandDepth=r.autoExpandDepth||0,this._createNodes())}_nodeToObjectID(e){return e.substring(this._baseId.length)}_objectToNodeID(e){return this._baseId+e}setAutoExpandDepth(e=0){this._autoExpandDepth=e}setHierarchy(e){this._hierarchy!==e&&(this._hierarchy=e,this._createNodes())}_createNodes(){switch(this._rootElement&&(this._rootElement.parentNode.removeChild(this._rootElement),this._rootElement=null),this._rootNodes=[],this._objectNodes={},this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this._treeViewPlugin.error("Failed to build storeys hierarchy for model '"+this._metaModel.id+"' - perhaps this model is not an IFC model?");break;case"types":this._createTypesNodes();break;case"containment":default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_findEmptyNodes(e=this._rootMetaObject,t=0){const i=this._treeViewPlugin.viewer.scene,s=e.children,r=e.id,o=i.objects[r];if(e._countEntities=0,o&&e._countEntities++,s)for(let t=0,i=s.length;t<i;t++){const i=s[t];i._countEntities=this._findEmptyNodes(i),e._countEntities+=i._countEntities}return e._countEntities}_createStoreysNodes(e=this._rootMetaObject,t,i,s){if(this._pruneEmptyNodes&&0===e._countEntities)return;const r=e.type,o=e.name,a=e.children,n=e.id;if("IfcBuilding"===r)t={nodeId:this._objectToNodeID(n),objectId:n,title:this._rootName||(o&&""!==o&&"Default"!==o?o:r),type:r,parent:null,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},this._rootNodes.push(t),this._objectNodes[t.objectId]=t;else if("IfcBuildingStorey"===r){if(!t)return void this._treeViewPlugin.error("Failed to build storeys hierarchy for model '"+this._metaModel.id+"' - model does not have an IfcBuilding object, or is not an IFC model");i={nodeId:this._objectToNodeID(n),objectId:n,title:o&&""!==o&&"Default"!==o?o:r,type:r,parent:t,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},t.children.push(i),this._objectNodes[i.objectId]=i,s={}}else if(i){if(this._viewer.scene.objects[n]){let e=(s=s||{})[r];if(!e){const t=i.objectId+"."+r;e={nodeId:this._objectToNodeID(t),objectId:t,title:r,type:r,parent:i,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},i.children.push(e),this._objectNodes[t]=e,s[r]=e}const t={nodeId:this._objectToNodeID(n),objectId:n,title:o&&""!==o&&"Default"!==o?o:r,type:r,parent:e,numEntities:0,numVisibleEntities:0,checked:!1,children:[]};e.children.push(t),this._objectNodes[t.objectId]=t}}if(a)for(let e=0,r=a.length;e<r;e++){const r=a[e];this._createStoreysNodes(r,t,i,s)}}_createTypesNodes(e=this._rootMetaObject,t,i){if(this._pruneEmptyNodes&&0===e._countEntities)return;const s=e.type,r=e.name,o=e.children,a=e.id;if("IfcBuilding"===s)t={nodeId:this._objectToNodeID(a),objectId:a,title:this._rootName||(r&&""!==r&&"Default"!==r?r:s),type:s,parent:null,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},this._rootNodes.push(t),this._objectNodes[t.objectId]=t,i={};else if(t){if(this._viewer.scene.objects[a]){var n=i[s];n||(n={nodeId:this._objectToNodeID(s),objectId:s,title:s,type:s,parent:t,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},t.children.push(n),this._objectNodes[n.objectId]=n,i[s]=n);const e={nodeId:this._objectToNodeID(a),objectId:a,title:r&&""!==r&&"Default"!==r?r:s,type:s,parent:n,numEntities:0,numVisibleEntities:0,checked:!1,children:[]};n.children.push(e),this._objectNodes[e.objectId]=e}}if(o)for(let e=0,s=o.length;e<s;e++){const s=o[e];this._createTypesNodes(s,t,i)}}_createContainmentNodes(e=this._rootMetaObject,t){if(this._pruneEmptyNodes&&0===e._countEntities)return;const i=e.type,s=e.name||i,r=e.children,o=e.id,a={nodeId:this._objectToNodeID(o),objectId:o,title:t?s&&""!==s&&"Default"!==s?s:i:this._rootName||s,type:i,parent:t,numEntities:0,numVisibleEntities:0,checked:!1,children:[]};if(t?t.children.push(a):this._rootNodes.push(a),this._objectNodes[a.objectId]=a,r)for(let e=0,t=r.length;e<t;e++){const t=r[e];this._createContainmentNodes(t,a)}}_doSortNodes(){for(let e=0,t=this._rootNodes.length;e<t;e++){const t=this._rootNodes[e];this._sortChildren(t)}}_sortChildren(e){const t=e.children;if(t&&0!==t.length){"storeys"===this._hierarchy&&"IfcBuilding"===e.type?t.sort(this._getSpatialSortFunc()):t.sort(this._alphaSortFunc);for(let e=0,i=t.length;e<i;e++){const i=t[e];this._sortChildren(i)}}}_getSpatialSortFunc(){const e=this._treeViewPlugin.viewer,t=e.scene,i=t.camera,s=e.metaScene;return this._spatialSortFunc||(this._spatialSortFunc=((e,r)=>{e.aabb&&r.aabb||(e.aabb||(e.aabb=t.getAABB(s.getObjectIDsInSubtree(e.objectId))),r.aabb||(r.aabb=t.getAABB(s.getObjectIDsInSubtree(r.objectId))));let o=0;return o=i.xUp?0:i.yUp?1:2,e.aabb[o]>r.aabb[o]?-1:e.aabb[o]<r.aabb[o]?1:0}))}_alphaSortFunc(e,t){const i=e.title.toUpperCase(),s=t.title.toUpperCase();return i<s?-1:i>s?1:0}_synchNodesToEntities(){const e=this._rootMetaObject.getObjectIDsInSubtree(),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;s<r;s++){const r=e[s];if(t[r]){const e=this._objectNodes[r];if(e){const t=i[r];if(t){const i=t.visible;e.numEntities=1,i?(e.numVisibleEntities=1,e.checked=!0):(e.numVisibleEntities=0,e.checked=!1);let s=e.parent;for(;s;)s.numEntities++,i&&(s.numVisibleEntities++,s.checked=!0),s=s.parent}}}}}_withNodeTree(e,t){t(e);const i=e.children;if(i)for(let e=0,s=i.length;e<s;e++)this._withNodeTree(i[e],t)}_createTrees(){if(0===this._rootNodes.length)return;const e=this._rootNodes.map(e=>this._createNodeElement(e)),t=document.createElement("ul");e.forEach(e=>{t.appendChild(e)}),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){const t=document.createElement("li"),i=this._objectToNodeID(e.objectId);if(t.id="node-"+i,e.children.length>0){const e="switch-"+i,s=document.createElement("a");s.href="#",s.id=e,s.textContent="+",s.classList.add("plus"),s.addEventListener("click",this.switchExpandHandler),t.appendChild(s)}const s=document.createElement("input");s.id=i,s.type="checkbox",s.checked=e.checked,s.addEventListener("change",this._checkboxChangeHandler),t.appendChild(s);const r=document.createElement("span");return r.textContent=e.title,t.appendChild(r),r.oncontextmenu=(t=>{this._treeViewPlugin.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()}),r.onclick=(t=>{this._treeViewPlugin.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()}),t}expandToDepth(e){const t=(i,s)=>{if(s===e)return;const r="switch-"+i.nodeId,o=document.getElementById(r);if(o){this._expandSwitchElement(o);const e=i.children;for(var a=0,n=e.length;a<n;a++){const i=e[a];t(i,s+1)}}};for(let e=0,i=this._rootNodes.length;e<i;e++){const i=this._rootNodes[e];t(i,0)}}collapse(){for(let e=0,t=this._rootNodes.length;e<t;e++){const t=this._rootNodes[e].objectId;this._collapseNode(t)}}showNode(e){this._showListItemElementId&&this.unShowNode();const t=this._objectNodes[e];if(!t)return;const i=t.nodeId,s="switch-"+i,r=document.getElementById(s);if(r)return this._expandSwitchElement(r),void r.scrollIntoView();const o=[];o.unshift(t);let a=t.parent;for(;a;)o.unshift(a),a=a.parent;for(let e=0,t=o.length;e<t;e++){const t="switch-"+o[e].nodeId,i=document.getElementById(t);i&&this._expandSwitchElement(i)}const n="node-"+i,l=document.getElementById(n);l.scrollIntoView({block:"center"}),l.classList.add("highlighted-node"),this._showListItemElementId=n}unShowNode(){if(!this._showListItemElementId)return;const e=document.getElementById(this._showListItemElementId);e?(e.classList.remove("highlighted-node"),this._showListItemElementId=null):this._showListItemElementId=null}_expandSwitchElement(e){const t=e.parentElement;if(t.getElementsByTagName("li")[0])return;const i=t.id.replace("node-",""),s=this._nodeToObjectID(i),r=this._objectNodes[s].children.map(e=>this._createNodeElement(e)),o=document.createElement("ul");r.forEach(e=>{o.appendChild(e)}),t.appendChild(o),e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",this.switchExpandHandler),e.addEventListener("click",this.switchCollapseHandler)}_collapseNode(e){const t="switch-"+this._objectToNodeID(e),i=document.getElementById(t);this._collapseSwitchElement(i)}_collapseSwitchElement(e){if(!e)return;const t=e.parentElement;if(!t)return;const i=t.querySelector("ul");i&&(t.removeChild(i),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",this.switchCollapseHandler),e.addEventListener("click",this.switchExpandHandler))}destroy(){this._rootElement&&!this._destroyed&&(this._rootElement.parentNode.removeChild(this._rootElement),this._viewer.scene.off(this._onObjectVisibility),this._destroyed=!0,idMap$1.removeItem(this._id))}}class TreeViewPlugin extends Plugin{constructor(e,t={}){if(super("TreeViewPlugin",e),t.containerElement){if(this._containerElement=t.containerElement,this._modelTreeViews={},this._modelTreeViews={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._pruneEmptyNodes=!1!==t.pruneEmptyNodes,this._autoAddModels){const e=Object.keys(this.viewer.scene.models);for(let t=0,i=e.length;t<i;t++){const i=e[t];this.addModel(i)}this.viewer.scene.on("modelLoaded",e=>{this.viewer.metaScene.metaModels[e]&&this.addModel(e)})}this.hierarchy=t.hierarchy}else this.error("Config expected: containerElement")}set hierarchy(e){"containment"!==(e=e||"containment")&&"storeys"!==e&&"types"!==e&&(this.error("Unsupported value for `hierarchy' - defaulting to 'containment'"),e="containment"),this._hierarchy=e;for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].setHierarchy(this._hierarchy)}get hierarchy(){return this._hierarchy}addModel(e,t={}){if(!this._containerElement)return;const i=this.viewer.scene.models[e];if(!i)throw"Model not found: "+e;const s=this.viewer.metaScene.metaModels[e];s?this._modelTreeViews[e]?this.warn("Model already added: "+e):(this._modelTreeViews[e]=new ModelTreeView(this.viewer,this,i,s,{containerElement:this._containerElement,autoExpandDepth:this._autoExpandDepth,hierarchy:this._hierarchy,sortNodes:this._sortNodes,pruneEmptyNodes:this._pruneEmptyNodes,rootName:t.rootName}),i.on("destroyed",()=>{this.removeModel(i.id)})):this.error("MetaModel not found: "+e)}removeModel(e){if(!this._containerElement)return;const t=this._modelTreeViews[e];t?(t.destroy(),delete this._modelTreeViews[e]):this.warn("Model not added: "+e)}collapse(){for(let e in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(e)){this._modelTreeViews[e].collapse()}}showNode(e){this.unShowNode();const t=this.viewer.metaScene.metaObjects[e];if(!t)return void this.error("MetaObject not found: "+e);const i=t.metaModel.id,s=this._modelTreeViews[i];s?s.showNode(e):this.error("Object not in this TreeView: "+e)}unShowNode(){for(let e in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(e)){this._modelTreeViews[e].unShowNode()}}expandToDepth(e){for(let t in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(t)){const i=this._modelTreeViews[t];i.collapse(),i.expandToDepth(e)}}withNodeTree(e,t){t(e);const i=e.children;if(i)for(let e=0,s=i.length;e<s;e++)this.withNodeTree(i[e],t)}destroy(){if(this._containerElement){for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].destroy();this._modelTreeViews={},super.destroy()}}}const tempVec3$4=math.vec3();class TreeViewContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"Isolate",doAction:function(e){const t=e.viewer,i=t.scene,s=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&s.push(e.objectId)});const r=i.getAABB(s);t.cameraControl.pivotPos=math.getAABB3Center(r,tempVec3$4),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsVisible(i.objectIds,!1),i.setObjectsPickable(i.objectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(s,!0),i.setObjectsPickable(s,!0),t.cameraFlight.flyTo({aabb:r},()=>{})}}],[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&s.push(e.objectId)}),i.setObjectsVisible(s,!0),i.setObjectsHighlighted(s,!0);const r=i.getAABB(s);t.cameraFlight.flyTo({aabb:r,duration:.5},()=>{setTimeout(function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)},500)}),t.cameraControl.pivotPos=math.getAABB3Center(r)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}}],[{title:"Hide",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!1)}})}},{title:"Hide Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.visibleObjectIds,!1),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),t.setObjectsHighlighted(t.highlightedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!0)}})}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.visibleObjectIds.length>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}}],[{title:"Show",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!0,i.xrayed&&(i.pickable=!0),i.xrayed=!1,i.selected=!1)}})}},{title:"Show Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!1)}})}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects<t.numObjects||e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.xrayed=!0,i.visible=!0,i.pickable=!1)}})}},{title:"Undo X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.xrayed=!1,i.pickable=!0)}})}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsHighlighted(t.highlightedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.xrayed=!1,i.pickable=!0)}})}},{title:"X-Ray All",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!0,i.visible=!0)}})}},{title:"Undo Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!1)}})}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}const tempVec3$5=math.vec3();class ObjectsExplorer extends Controller{constructor(e,t={}){if(super(e),!t.objectsTabElement)throw"Missing config: objectsTabElement";if(!t.showAllObjectsButtonElement)throw"Missing config: showAllObjectsButtonElement";if(!t.hideAllObjectsButtonElement)throw"Missing config: hideAllObjectsButtonElement";if(!t.objectsElement)throw"Missing config: objectsElement";if(this._objectsTabElement=t.objectsTabElement,this._showAllObjectsButtonElement=t.showAllObjectsButtonElement,this._hideAllObjectsButtonElement=t.hideAllObjectsButtonElement,this._objectsTabButtonElement=this._objectsTabElement.querySelector(".xeokit-tab-btn"),!this._objectsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";const i=t.objectsElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,hierarchy:"containment",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse()})}setEnabled(e){e?(this._objectsTabButtonElement.classList.remove("disabled"),this._showAllObjectsButtonElement.classList.remove("disabled"),this._hideAllObjectsButtonElement.classList.remove("disabled")):(this._objectsTabButtonElement.classList.add("disabled"),this._showAllObjectsButtonElement.classList.add("disabled"),this._hideAllObjectsButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$6=math.vec3();class ClassesExplorer extends Controller{constructor(e,t={}){if(super(e),!t.classesTabElement)throw"Missing config: classesTabElement";if(!t.showAllClassesButtonElement)throw"Missing config: showAllClassesButtonElement";if(!t.hideAllClassesButtonElement)throw"Missing config: hideAllClassesButtonElement";if(!t.classesElement)throw"Missing config: classesElement";if(this._classesTabElement=t.classesTabElement,this._showAllClassesButtonElement=t.showAllClassesButtonElement,this._hideAllClassesButtonElement=t.hideAllClassesButtonElement,this._classesTabButtonElement=this._classesTabElement.querySelector(".xeokit-tab-btn"),!this._classesTabButtonElement)throw"Missing DOM element: xeokit-tab-btn";const i=t.classesElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,hierarchy:"types",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse()})}setEnabled(e){e?(this._classesTabButtonElement.classList.remove("disabled"),this._showAllClassesButtonElement.classList.remove("disabled"),this._hideAllClassesButtonElement.classList.remove("disabled")):(this._classesTabButtonElement.classList.add("disabled"),this._showAllClassesButtonElement.classList.add("disabled"),this._hideAllClassesButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$7=math.vec3();class StoreysExplorer extends Controller{constructor(e,t={}){if(super(e),!t.storeysTabElement)throw"Missing config: storeysTabElement";if(!t.showAllStoreysButtonElement)throw"Missing config: showAllStoreysButtonElement";if(!t.hideAllStoreysButtonElement)throw"Missing config: hideAllStoreysButtonElement";if(!t.storeysElement)throw"Missing config: storeysElement";if(this._storeysTabElement=t.storeysTabElement,this._showAllStoreysButtonElement=t.showAllStoreysButtonElement,this._hideAllStoreysButtonElement=t.hideAllStoreysButtonElement,this._storeysTabButtonElement=this._storeysTabElement.querySelector(".xeokit-tab-btn"),!this._storeysTabButtonElement)throw"Missing DOM element: .xeokit-tab-btn";const i=t.storeysElement;this._treeView=new TreeViewPlugin(this.viewer,{containerElement:i,autoAddModels:!1,hierarchy:"storeys",autoExpandDepth:1}),this._treeViewContextMenu=new TreeViewContextMenu,this._treeView.on("contextmenu",e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode,pruneEmptyNodes:!0},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)}),this._treeView.on("nodeTitleClicked",e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,e=>{e.objectId&&i.push(e.objectId)}),e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))}),this._onModelLoaded=this.viewer.scene.on("modelLoaded",e=>{const t=this.bimViewer._modelsExplorer.getModelInfo(e);t&&this._treeView.addModel(e,{rootName:t.name})}),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)}),this.bimViewer.on("reset",()=>{this._treeView.collapse(),this._treeView.expandToDepth(1)})}setEnabled(e){e?(this._storeysTabButtonElement.classList.remove("disabled"),this._showAllStoreysButtonElement.classList.remove("disabled"),this._hideAllStoreysButtonElement.classList.remove("disabled")):(this._storeysTabButtonElement.classList.add("disabled"),this._showAllStoreysButtonElement.classList.add("disabled"),this._hideAllStoreysButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];if(!i)return void this.error("selectStorey() - object is not found: '"+e+"'");if("IfcBuildingStorey"!==i.type)return void this.error("selectStorey() - object is not found: '"+e+"'");const s=i.getObjectIDsInSubtree();this._selectObjects(s,t)}_selectObjects(e,t){const i=this.viewer.scene,s=i.getAABB(e);this.viewer.cameraControl.pivotPos=math.getAABB3Center(s,tempVec3$7),t?(i.setObjectsXRayed(i.objectIds,!0),i.setObjectsVisible(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsXRayed(e,!1),i.setObjectsVisible(e,!0),i.setObjectsPickable(e,!0),this.viewer.cameraFlight.flyTo({aabb:s},()=>{setTimeout(function(){i.setObjectsVisible(i.xrayedObjectIds,!1),i.setObjectsXRayed(i.xrayedObjectIds,!1)},500),t()})):(i.setObjectsVisible(i.objectIds,!1),i.setObjectsPickable(i.xrayedObjectIds,!0),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(e,!0),this.viewer.cameraFlight.jumpTo({aabb:s}))}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const tempVec3$8=math.vec3(),newLook=math.vec3(),newEye=math.vec3(),newUp=math.vec3(),newLookEyeVec=math.vec3();class CameraFlightAnimation extends Component{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=math.vec3(),this._eye1=math.vec3(),this._up1=math.vec3(),this._look2=math.vec3(),this._eye2=math.vec3(),this._up2=math.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,a,n,l,h;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)a=e.eye,n=e.look,l=e.up;else if(e.eye)a=e.eye;else if(e.look)n=e.look;else{let s=e;if((utils.isNumeric(s)||utils.isString(s))&&(h=s,!(s=this.scene.components[h])))return this.error("Component not found: "+utils.inQuotes(h)),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=math.getAABB3Center(o);this._look2=c||t;const i=math.subVec3(this._eye1,this._look1,tempVec3$8),s=math.normalizeVec3(i),r=c?math.getAABB3DiagPoint(o,c):math.getAABB3Diag(o),a=e.fitFOV||this._fitFOV,n=Math.abs(r/Math.tan(a*math.DEGTORAD));this._orthoScale2=1.1*r,this._eye2[0]=this._look2[0]+s[0]*n,this._eye2[1]=this._look2[1]+s[1]*n,this._eye2[2]=this._look2[2]+s[2]*n,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(a||n||l)&&(this._flyingEyeLookUp=!!a&&!!n&&!!l,this._flyingEye=!!a&&!n,this._flyingLook=!!n&&!a,a&&(this._eye2[0]=a[0],this._eye2[1]=a[1],this._eye2[2]=a[2]),n&&(this._look2[0]=n[0],this._look2[1]=n[1],this._look2[2]=n[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(),s.ortho.scale=this._orthoScale2,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+(e.duration?1e3*e.duration:this._duration),this._flying=!0,core.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,a;if(e.aabb)i=e.aabb;else if(6===e.length)i=e;else if(e.eye||e.look||e.up)r=e.eye,o=e.look,a=e.up;else{let t=e;if((utils.isNumeric(t)||utils.isString(t))&&(s=t,!(t=this.scene.components[s])))return void this.error("Component not found: "+utils.inQuotes(s));i=t.aabb||this.scene.aabb}const n=e.poi;if(i){if(i[3]<=i[0]||i[4]<=i[1]||i[5]<=i[2])return;var l=n?math.getAABB3DiagPoint(i,n):math.getAABB3Diag(i);let s;o=n||math.getAABB3Center(i,o),this._trail?math.subVec3(t.look,o,newLookEyeVec):math.subVec3(t.eye,t.look,newLookEyeVec),math.normalizeVec3(newLookEyeVec),s=(void 0!==e.fit?e.fit:this._fit)?Math.abs(l/Math.tan((e.fitFOV||this._fitFOV)*math.DEGTORAD)):math.lenVec3(math.subVec3(t.eye,t.look,tempVec3$8)),math.mulVec3Scalar(newLookEyeVec,s),t.eye=math.addVec3(o,newLookEyeVec,tempVec3$8),t.look=o,this.scene.camera.ortho.scale=1.1*l}else(r||o||a)&&(r&&(t.eye=r),o&&(t.look=o),a&&(t.up=a));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const i=this.easing?CameraFlightAnimation._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(math.subVec3(s.eye,s.look,newLookEyeVec),s.eye=math.lerpVec3(i,0,1,this._eye1,this._eye2,newEye),s.look=math.subVec3(newEye,newLookEyeVec,newLook)):this._flyingLook&&(s.look=math.lerpVec3(i,0,1,this._look1,this._look2,newLook),s.up=math.lerpVec3(i,0,1,this._up1,this._up2,newUp)):this._flyingEyeLookUp&&(s.eye=math.lerpVec3(i,0,1,this._eye1,this._eye2,newEye),s.look=math.lerpVec3(i,0,1,this._look1,this._look2,newLook),s.up=math.lerpVec3(i,0,1,this._up1,this._up2,newUp)),this._projection2){const t="ortho"===this._projection2?CameraFlightAnimation._easeOutExpo(e,0,1,1):CameraFlightAnimation._easeInCubic(e,0,1,1);s.customProjection.matrix=math.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);t?this.stop():core.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=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()}}const screenPos=math.vec4(),viewPos=math.vec4(),worldPos=math.vec4(),tempVec3a$3=math.vec3();class PanController{constructor(e){this._scene=e,this._inverseProjectMat=math.mat4(),this._transposedProjectMat=math.mat4(),this._inverseViewMat=math.mat4(),this._projMatDirty=!0,this._viewMatDirty=!0,this._sceneDiagSizeDirty=!0,this._sceneDiagSize=1,this._onCameraProjMatrix=this._scene.camera.on("projMatrix",()=>{this._projMatDirty=!0}),this._onCameraViewMatrix=this._scene.camera.on("viewMatrix",()=>{this._viewMatDirty=!0}),this._onSceneBoundary=this._scene.scene.on("boundary",()=>{this._sceneDiagSizeDirty=!0})}_getInverseProjectMat(){return this._projMatDirty&&math.inverseMat4(this._scene.camera.projMatrix,this._inverseProjectMat),this._inverseProjectMat}_getTransposedProjectMat(){return this._projMatDirty&&math.transposeMat4(this._scene.camera.projMatrix,this._transposedProjectMat),this._transposedProjectMat}_getInverseViewMat(){return this._viewMatDirty&&math.inverseMat4(this._scene.camera.viewMatrix,this._inverseViewMat),this._inverseViewMat}_getSceneDiagSize(){return this._sceneDiagSizeDirty&&(this._sceneDiagSize=math.getAABB3Diag(this._scene.aabb)),this._sceneDiagSize}_unproject(e,t,i,s){const r=this._scene.canvas.canvas,o=this._getInverseProjectMat(),a=this._getInverseViewMat(),n=r.offsetWidth/2,l=r.offsetHeight/2;screenPos[0]=(e[0]-n)/n,screenPos[1]=(e[1]-l)/l,screenPos[2]=t,screenPos[3]=1,math.mulMat4v4(o,screenPos,i),math.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,math.mulMat4v4(a,i,s)}dollyToCanvasPos(e,t){const i=this._getTransposedProjectMat(),s=i.subarray(8,12),r=i.subarray(12),o=[0,0,-this._getSceneDiagSize(),1],a=math.dotVec4(o,s)/math.dotVec4(o,r);this._unproject(e,a,viewPos,worldPos),this.dollyToWorldPos(worldPos,t)}dollyToWorldPos(e,t){const i=this._scene.camera,s=math.subVec3(e,i.eye,tempVec3a$3);if(math.lenVec3(s)<t)return;math.normalizeVec3(s);const r=s[0]*t,o=s[1]*t,a=s[2]*t,n=i.eye,l=i.look;i.eye=[n[0]+r,n[1]+o,n[2]+a],i.look=[l[0]+r,l[1]+o,l[2]+a]}destroy(){this._scene.camera.off(this._onCameraProjMatrix),this._scene.camera.off(this._onCameraViewMatrix),this._scene.scene.off(this._onSceneBoundary)}}class PivotController{constructor(e){this._scene=e,this._pivotWorldPos=math.vec3(),this._cameraOffset=math.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivoting=!1,this._shown=!1,this._pivotViewPos=math.vec4(),this._pivotProjPos=math.vec4(),this._pivotCanvasPos=math.vec2(),this._cameraDirty=!0,this._scene.camera.on("viewMatrix",()=>{this._cameraDirty=!0}),this._scene.camera.on("projMatrix",()=>{this._cameraDirty=!0}),this._scene.on("tick",()=>{this.updatePivotElement()})}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){math.transformPoint3(e.viewMatrix,this._pivotWorldPos,this._pivotViewPos),this._pivotViewPos[3]=1,math.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);const o=t.canvas.getBoundingClientRect();this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-12+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-12+"px"),this._cameraDirty=!1}}setPivotElement(e){this._pivotElement=e}startPivot(e){e&&this._pivotWorldPos.set(e);const t=this._scene.camera;let i=math.lookAtMat4v(t.eye,t.look,t.worldUp);math.transformPoint3(i,this._pivotWorldPos,this._cameraOffset),this._cameraOffset[2]+=math.distVec3(t.eye,this._pivotWorldPos),i=math.inverseMat4(i);const s=math.transformVec3(i,this._cameraOffset),r=math.vec3();if(math.subVec3(t.eye,this._pivotWorldPos,r),math.addVec3(r,s),t.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=math.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e)}getPivotPos(){return this._pivotWorldPos}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=math.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const a=math.lenVec3(math.subVec3(i.look,i.eye,math.vec3()));math.addVec3(o,this._pivotWorldPos);let n=math.lookAtMat4v(o,this._pivotWorldPos,i.worldUp);n=math.inverseMat4(n);const l=math.transformVec3(n,this._cameraOffset);n[12]-=l[0],n[13]-=l[1],n[14]-=l[2];const h=[n[8],n[9],n[10]];i.eye=[n[12],n[13],n[14]],math.subVec3(i.eye,math.mulVec3Scalar(h,a),i.look),i.up=[n[4],n[5],n[6]],this.showPivot()}showPivot(){this._shown||(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible",this._shown=!0,this._hideTimeout=window.setTimeout(()=>{console.log("timeout"),this.hidePivot()},1e3)))}hidePivot(){this._shown&&(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._shown=!1)}endPivot(){this._pivoting=!1}}class PickController{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.pickCursorPos=math.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._onTick=this._scene.on("tick",()=>{this.update()})}update(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){if(this.picked=!1,this.pickedSurface=!1,this.schedulePickSurface||this._cameraControl.hasSubs("hoverSurface")?this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!0,canvasPos:this.pickCursorPos}):this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult){this.picked=!0;const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e),this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.schedulePickEntity=!1,this.schedulePickSurface=!1}}destroy(){this._scene.off(this._onTick)}}const canvasPos=math.vec2(),getCanvasPosFromEvent=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class MousePanRotateDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let a,n,l,h,c=0,d=0;this._down=!1;let u=!1;const p=math.vec3(),m=this._scene.canvas.canvas,_=[];document.addEventListener("keydown",this._documentKeyDownHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;_[r]=!0})),document.addEventListener("keyup",this._documentKeyUpHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;_[r]=!1})),m.addEventListener("mousedown",this._mouseDownHandler=(t=>{if(i.active&&i.pointerEnabled)switch(this._down=!0,t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(m.style.cursor="move",a=s.mouseCanvasPos[0],n=s.mouseCanvasPos[1],c=s.mouseCanvasPos[0],d=s.mouseCanvasPos[1],o.pickCursorPos=s.mouseCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult?(u=!0,p.set(o.pickResult.worldPos)):u=!1):(m.style.cursor="move",a=s.mouseCanvasPos[0],n=s.mouseCanvasPos[1],c=s.mouseCanvasPos[0],d=s.mouseCanvasPos[1]);break;case 2:l=!0,i.panRightClick||(m.style.cursor="move",a=s.mouseCanvasPos[0],n=s.mouseCanvasPos[1],c=s.mouseCanvasPos[0],d=s.mouseCanvasPos[1]);break;case 3:h=!0,i.panRightClick&&(m.style.cursor="move",a=s.mouseCanvasPos[0],n=s.mouseCanvasPos[1],c=s.mouseCanvasPos[0],d=s.mouseCanvasPos[1],o.pickCursorPos=s.mouseCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult?(u=!0,p.set(o.pickResult.worldPos)):u=!1)}})),m.addEventListener("mousemove",this._mouseMoveHandler=(t=>{if(!i.active||!i.pointerEnabled)return;if(!s.mouseover)return;if(r.inputFromMouse=!0,!this._down)return;const o=e.canvas.boundary,c=o[2]-o[0],d=o[3]-o[1],m=s.mouseCanvasPos[0],g=s.mouseCanvasPos[1];if(_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&l||i.panRightClick&&h){const t=m-a,i=g-n,s=e.camera;if("perspective"===s.projection){const o=Math.abs(u?math.lenVec3(math.subVec3(p,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/d,r.panDeltaY+=1.5*i*o/d}else r.panDeltaX+=.5*s.ortho.scale*(t/d),r.panDeltaY+=.5*s.ortho.scale*(i/d)}else i.planView||(r.rotateDeltaY-=(m-a)/c*i.dragRotationRate/2,r.rotateDeltaX+=(g-n)/d*(i.dragRotationRate/4));a=m,n=g})),m.addEventListener("mouseup",this._mouseUpHandler=(e=>{if(i.active&&i.pointerEnabled){switch(e.which){case 1:break;case 2:l=!1;break;case 3:h=!1,getCanvasPosFromEvent(e,canvasPos);const i=canvasPos[0],s=canvasPos[1];Math.abs(i-c)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{canvasPos:canvasPos,event:e},!0)}m.style.removeProperty("cursor"),this._down=!1}})),m.addEventListener("mouseenter",this._mouseEnterHandler=(()=>{i.active&&i.pointerEnabled&&(this._down=!1)})),m.addEventListener("mouseleave",this._mouseLeaveHandler=(()=>{i.active&&i.pointerEnabled&&(r.panDeltaX=0,r.panDeltaY=0,r.rotateDeltaX=0,r.rotateDeltaY=0,this._down=!1)}));let g=null;m.addEventListener("wheel",this._mouseWheelHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var s=null!==g?t-g:0;g=t,s>.05&&(s=.05),s<1/60&&(s=1/60);const o=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===o)return;const a=o/Math.abs(o);r.dollyDelta+=-a*s*i.mouseWheelDollyRate,e.preventDefault()}))}reset(){this._down=!1}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const center=math.vec3(),tempVec3a$4=math.vec3(),tempVec3b$3=math.vec3(),tempVec3c$3=math.vec3(),tempVec3d$1=math.vec3(),tempCameraTarget={eye:math.vec3(),look:math.vec3(),up:math.vec3()};class KeyboardAxisViewHandler{constructor(e,t,i,s,r){this._scene=e;const o=e.input,a=e.camera;document.addEventListener("keydown",this._documentKeyDownHandler=(r=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r.keyCode;if(n!==o.KEY_NUM_1&&n!==o.KEY_NUM_2&&n!==o.KEY_NUM_3&&n!==o.KEY_NUM_4&&n!==o.KEY_NUM_5&&n!==o.KEY_NUM_6)return;const l=e.aabb,h=math.getAABB3Diag(l);math.getAABB3Center(l,center);const c=Math.abs(h/Math.tan(t.cameraFlight.fitFOV*math.DEGTORAD));switch(n){case o.KEY_NUM_1:tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldRight,c,tempVec3a$4),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp);break;case o.KEY_NUM_2:tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldForward,c,tempVec3a$4),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp);break;case o.KEY_NUM_3:tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldRight,-c,tempVec3a$4),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp);break;case o.KEY_NUM_4:tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldForward,-c,tempVec3a$4),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(a.worldUp);break;case o.KEY_NUM_5:tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldUp,c,tempVec3a$4),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(a.worldForward,1,tempVec3b$3),tempVec3c$3));break;case o.KEY_NUM_6:tempCameraTarget.eye.set(math.addVec3(center,math.mulVec3Scalar(a.worldUp,-c,tempVec3a$4),tempVec3d$1)),tempCameraTarget.look.set(center),tempCameraTarget.up.set(math.normalizeVec3(math.mulVec3Scalar(a.worldForward,-1,tempVec3b$3)));break;default:return}!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(center),t.cameraFlight.duration>0?t.cameraFlight.flyTo(tempCameraTarget,()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()}):(t.cameraFlight.jumpTo(tempCameraTarget),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){document.removeEventListener("keydown",this._documentKeyDownHandler)}}class MousePickHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;const l=this._scene.canvas.canvas,h=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;math.subVec3(i.eye,i.look,[]);t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};l.addEventListener("mousemove",this._canvasMouseMoveHandler=(t=>{if(!i.active||!i.pointerEnabled)return;const r=n.hasSubs("hover"),a=n.hasSubs("hoverOut"),l=n.hasSubs("hoverOff"),h=n.hasSubs("hoverSurface");if(r||a||l||h)if(o.pickCursorPos=s.mouseCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),n.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t),n.fire("hover",o.pickResult,!0),o.pickResult.worldPos&&n.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),n.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)})),l.addEventListener("mousedown",this._canvasMouseDownHandler=(e=>{i.active&&i.pointerEnabled&&(s.mouseDownClientX=e.clientX,s.mouseDownClientY=e.clientY,s.mouseDownCursorX=s.mouseCanvasPos[0],s.mouseDownCursorY=s.mouseCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.mouseCanvasPos,o.schedulePickSurface=!0,o.update(),1===e.which&&(o.pickResult?a.startPivot(o.pickResult.worldPos):a.startPivot())))})),l.addEventListener("mouseup",this._canvasMouseUpHandler=(r=>{if(!i.active||!i.pointerEnabled)return;if(a.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=n.hasSubs("picked"),c=n.hasSubs("pickedNothing"),d=n.hasSubs("pickedSurface"),u=n.hasSubs("doublePicked"),p=n.hasSubs("doublePickedSurface"),m=n.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||m))return(l||c||d)&&(o.pickCursorPos=s.mouseCanvasPos,o.schedulePickSurface=d,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&n.fire("pickedSurface",o.pickResult,!0)):n.fire("pickedNothing",{},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks)this._timeout=setTimeout(()=>{o.pickCursorPos=s.mouseCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=d,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&(n.fire("pickedSurface",o.pickResult,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.startPivot(o.pickResult.worldPos),t.pivotController.showPivot()))):n.fire("pickedNothing",{},!0),this._clicks=0},250);else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.mouseCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(n.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(h(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=math.getAABB3Center(e);t.pivotController.startPivot(i),t.pivotController.showPivot()}}else if(n.fire("doublePickedNothing",!0),i.doublePickFlyTo&&(h(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=math.getAABB3Center(i);t.pivotController.startPivot(s),t.pivotController.showPivot()}this._clicks=0}}),!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class KeyboardPanRotateDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=e.input,a=[],n=e.canvas.canvas;document.addEventListener("keydown",this._documentKeyDownHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!0,r===o.KEY_SHIFT&&(n.style.cursor="move")})),document.addEventListener("keyup",this._documentKeyUpHandler=(t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!1,r===o.KEY_SHIFT&&(n.style.cursor="default")})),this._onTick=e.on("tick",n=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const l=n.deltaTime/1e3;if(!i.planView){const e=a[o.KEY_LEFT_ARROW],s=a[o.KEY_RIGHT_ARROW],n=a[o.KEY_UP_ARROW],h=a[o.KEY_DOWN_ARROW],c=l*i.keyboardRotationRate;let d,u;(e||s||n||h)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),s?r.rotateDeltaY-=c:e&&(r.rotateDeltaY+=c),h?r.rotateDeltaX+=c:n&&(r.rotateDeltaX-=c)),"azerty"===i.keyboardLayout?(d=a[o.KEY_A],u=a[o.KEY_E]):(d=a[o.KEY_Q],u=a[o.KEY_E]),(u||d)&&(d?r.rotateDeltaY+=c:u&&(r.rotateDeltaY-=c),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){const e=a[o.KEY_ADD],s=a[o.KEY_SUBTRACT];if(e||s){const o=l*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),s?r.dollyDelta+=o:e&&(r.dollyDelta-=o)}}let h,c,d,u,p,m;const _=(a[o.KEY_ALT]?.3:1)*l*i.keyboardPanRate;"azerty"===i.keyboardLayout?(h=a[o.KEY_Z],c=a[o.KEY_S],d=a[o.KEY_Q],u=a[o.KEY_D],p=a[o.KEY_W],m=a[o.KEY_X]):(h=a[o.KEY_W],c=a[o.KEY_S],d=a[o.KEY_A],u=a[o.KEY_D],p=a[o.KEY_Z],m=a[o.KEY_X]),(h||c||d||u||p||m)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=_:p&&(r.panDeltaY+=-_),u?r.panDeltaX+=-_:d&&(r.panDeltaX+=_),c?r.panDeltaZ+=_:h&&(r.panDeltaZ+=-_))})}reset(){}destroy(){this._scene.off(this._onTick),document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler)}}const SCALE_DOLLY_EACH_FRAME=5,EPSILON=.001,tempVec3$9=math.vec3();class CameraUpdater{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,a=t.pivotController,n=t.panController;let l=SCALE_DOLLY_EACH_FRAME,h=1;this._onTick=e.on("tick",t=>{if(!i.active||!i.pointerEnabled)return;let c="default";t.deltaTime;if(Math.abs(r.dollyDelta)<EPSILON&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<EPSILON&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<EPSILON&&(r.rotateDeltaY=0),i.firstPerson&&!i.followPointer);else if(--l<=0&&(l=SCALE_DOLLY_EACH_FRAME,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX){const e=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:s.mouseCanvasPos});if(e&&e.worldPos){const t=e.worldPos;a.setPivotPos(t),a.hidePivot()}else h=1}const t=Math.abs(math.lenVec3(math.subVec3(a.getPivotPos(),e.camera.eye,tempVec3$9)));(h=t/i.dollyProximityThreshold)<i.dollyMinSpeed&&(h=i.dollyMinSpeed)}let d=r.dollyDelta*h;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(a.getPivoting()&&i.followPointer?(a.continuePivot(r.rotateDeltaY,r.rotateDeltaX),a.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?o.pitch(-r.rotateDeltaX):o.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?o.yaw(r.rotateDeltaY):o.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,c="grabbing"),Math.abs(r.panDeltaX)<EPSILON&&(r.panDeltaX=0),Math.abs(r.panDeltaY)<EPSILON&&(r.panDeltaY=0),Math.abs(r.panDeltaZ)<EPSILON&&(r.panDeltaZ=0),0!==r.panDeltaX||0!==r.panDeltaY||0!==r.panDeltaZ){a.getPivoting()&&i.followPointer&&a.showPivot();const e=math.vec3();let t,s;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){o.xUp?(t=o.eye[0],s=o.look[0]):o.yUp?(t=o.eye[1],s=o.look[1]):o.zUp&&(t=o.eye[2],s=o.look[2]),o.pan(e);const i=o.eye,r=o.look;o.xUp?(i[0]=t,r[0]=s):o.yUp?(i[1]=t,r[1]=s):o.zUp&&(i[2]=t,r[2]=s),o.eye=i,o.look=r}else o.pan(e);c="grabbing"}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==d){if(c=d<0?"zoom-in":"zoom-out",i.firstPerson){let e,t;if(i.constrainVertical&&(o.xUp?(e=o.eye[0],t=o.look[0]):o.yUp?(e=o.eye[1],t=o.look[1]):o.zUp&&(e=o.eye[2],t=o.look[2])),r.inputFromMouse&&i.followPointer?n.dollyToCanvasPos(s.mouseCanvasPos,-d):o.pan([0,0,d]),i.constrainVertical){const i=o.eye,s=o.look;o.xUp?(i[0]=e,s[0]=t):o.yUp?(i[1]=e,s[1]=t):o.zUp&&(i[2]=e,s[2]=t),o.eye=i,o.look=s}}else i.planView?r.inputFromMouse&&i.followPointer?d>0?o.pan([0,0,d]):n.dollyToWorldPos(a.getPivotPos(),-d):o.pan([0,0,d]):i.followPointer?n.dollyToWorldPos(a.getPivotPos(),-d):o.zoom(d);o.ortho.scale=o.ortho.scale+.5*d,r.dollyDelta*=i.dollyInertia}document.body.style.cursor=c})}destroy(){this._scene.off(this._onTick)}}class MouseMiscHandler{constructor(e,t,i,s,r){this._scene=e;const o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=(()=>{s.mouseover=!0})),o.addEventListener("mouseleave",this._mouseLeaveHandler=(()=>{s.mouseover=!1,o.style.cursor="default"})),o.addEventListener("mousemove",this._mouseMoveHandler=(e=>{getCanvasPosFromEvent$1(e,s.mouseCanvasPos)})),o.addEventListener("mousedown",this._mouseDownHandler=(e=>{i.active&&i.pointerEnabled&&(getCanvasPosFromEvent$1(e,s.mouseCanvasPos),s.mouseover=!0)})),o.addEventListener("mouseup",this._mouseUpHandler=(e=>{i.active&&i.pointerEnabled}))}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function getCanvasPosFromEvent$1(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t}class TouchPanRotateAndDollyHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=new Float32Array(2);let l=-1;const h=[];let c=0;const d=new Float32Array(2),u=new Float32Array(2);let p=0,m=Date.now();const _=e=>{const t=Date.now();return 0===p?(p=e,!0):p===e?t-m>50:(p=e,m=t,!1)},g=this._scene.canvas.canvas;g.addEventListener("touchstart",this._canvasTouchStartHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=e.touches,r=e.changedTouches;for(s.touchStartTime=Date.now(),1===t.length&&1===r.length?(l=s.touchStartTime,n[0]=t[0].pageX,n[1]=t[0].pageY,i.followPointer&&(o.pickCursorPos=n,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult?(a.startPivot(o.pickResult.worldPos),a.showPivot()):(a.startPivot(),a.showPivot()))):l=-1;h.length<t.length;)h.push(new Float32Array(2));for(let e=0,i=t.length;e<i;++e)h[e][0]=t[e].pageX,h[e][1]=t[e].pageY;p=0,c=t.length,e.stopPropagation()}),{passive:!0}),g.addEventListener("touchmove",this._canvasTouchMoveHandler=(t=>{if(!i.active||!i.pointerEnabled)return;const s=e.canvas.boundary,o=s[2]-s[0],a=s[3]-s[1],n=(i.firstPerson,180),l=t.touches;if(1===c){const e=l[0];_(1)&&(r.rotateDeltaY-=(e.pageX-h[0][0])/o*n*i.dragRotationRate,r.rotateDeltaX+=(e.pageY-h[0][1])/a*n*i.dragRotationRate)}else if(2===c){const t=l[0],i=l[1];math.subVec2([t.pageX,t.pageY],h[0],d),math.subVec2([i.pageX,i.pageY],h[1],u);const s=math.dotVec2(d,u)>0;if(s&&_(2)){math.subVec2([t.pageX,t.pageY],h[0],d);const i=d[0],s=d[1],o=e.camera;if("perspective"===o.projection){const t=Math.abs(e.camera.eyeLookDist)*Math.tan(o.perspective.fov/2*Math.PI/180);r.panDeltaX+=i*t/a,r.panDeltaY+=s*t/a}else r.panDeltaX+=.5*o.ortho.scale*(i/a),r.panDeltaY+=.5*o.ortho.scale*(s/a)}if(!s&&_(4)){const e=math.distVec2([t.pageX,t.pageY],[i.pageX,i.pageY]),s=math.distVec2(h[0],h[1]);r.dollyDelta=s-e}}for(let e=0;e<c;++e)h[e][0]=l[e].pageX,h[e][1]=l[e].pageY;t.stopPropagation()}),{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler)}}class TouchPickHandler{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=t.cameraControl,l=e.canvas.canvas;let h;const c=[],d=new Float32Array(2);let u=-1,p=-1;const m=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;math.subVec3(i.eye,i.look,[]);t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};l.addEventListener("touchstart",this._canvasTouchStartHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=e.touches,s=e.changedTouches;for(h=Date.now(),1===t.length&&1===s.length?(u=h,d[0]=t[0].pageX,d[1]=t[0].pageY):u=-1;c.length<t.length;)c.push(new Float32Array(2));for(let e=0,i=t.length;e<i;++e)c[e][0]=t[e].pageX,c[e][1]=t[e].pageY;c.length=t.length,e.stopPropagation()}),{passive:!0}),l.addEventListener("touchend",this._canvasTouchEndHandler=(e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),s=e.touches,r=e.changedTouches;0===s.length&&1===r.length&&u>-1&&t-u<i.tapInterval&&(p>-1&&u-p<i.doubleTapInterval?(o.pickCursorPos[0]=Math.round(r[0].clientX),o.pickCursorPos[1]=Math.round(r[0].clientY),o.schedulePickEntity=!0,o.schedulePickSurface=!!n.hasSubs("pickedSurface"),o.update(),o.pickResult?(o.pickResult?a.startPivot(o.pickResult.worldPos):a.startPivot(),n.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&m(o.pickResult)):(n.fire("doublePickedNothing",!0),i.doublePickFlyTo&&m()),p=-1):math.distVec2(c[0],d)<i.tapDistanceThreshold&&(o.pickCursorPos[0]=Math.round(r[0].clientX),o.pickCursorPos[1]=Math.round(r[0].clientY),o.schedulePickEntity=!0,o.schedulePickSurface=!!n.hasSubs("pickedSurface"),o.update(),o.pickResult?(o.pickResult?a.startPivot(o.pickResult.worldPos):a.startPivot(),n.fire("picked",o.pickResult,!0),o.pickedSurface&&n.fire("pickedSurface",o.pickResult,!0)):n.fire("pickedNothing",{},!0),p=t),u=-1),c.length=s.length;for(let e=0,t=s.length;e<t;++e)c[e][0]=s[e].pageX,c[e][1]=s[e].pageY;e.stopPropagation()}),{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class CameraControl extends Component{constructor(e,t={}){super(e,t),this.scene.canvas.canvas.oncontextmenu=(e=>{e.preventDefault()}),this._configs={tapInterval:150,doubleTapInterval:325,tapDistanceThreshold:4,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!1,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:.5,keyboardPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:10,dollyInertia:.75,dollyProximityThreshold:30,dollyMinSpeed:1},this._states={mouseCanvasPos:new Float32Array(2),mouseover:!1,inputFromMouse:!1,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:new Float32Array(2),tapStartTime:-1,lastTapTime:-1},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new PickController(this,this._configs),pivotController:new PivotController(i),panController:new PanController(this.scene),cameraFlight:new CameraFlightAnimation(this,{duration:.5})},this._handlers=[new MouseMiscHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new TouchPanRotateAndDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new MousePanRotateDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new KeyboardAxisViewHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new MousePickHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new TouchPickHandler(this.scene,this._controllers,this._configs,this._states,this._updates),new KeyboardPanRotateDollyHandler(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new CameraUpdater(this.scene,this._controllers,this._configs,this._states,this._updates),this.planView=t.planView,this.navMode=t.navMode,this.constrainVertical=t.constrainVertical,this.keyboardLayout=t.keyboardLayout,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){this._configs.active=!1!==e}get active(){return this._configs.active}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!!e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=value}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=void 0!==e&&null!==e?e:.5}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!==e&&void 0!==e?e:5}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!==e&&void 0!==e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!==e&&void 0!==e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!==e&&void 0!==e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!==e&&void 0!==e?e:15}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=void 0!==e&&null!==e?e:.75}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=void 0!==e&&null!==e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=void 0!==e&&null!==e?e:.05}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=void 0!==e&&null!==e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e}get keyboardLayout(){return this._configs.keyboardLayout}destroy(){this._destroyHandlers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}}class MetaModel{constructor(e,t,i,s,r,o,a,n,l){this.id=t,this.projectId=i,this.revisionId=s,this.author=r,this.createdAt=o,this.creatingApplication=a,this.schema=n,this.metaScene=e,this.rootMetaObject=l}getJSON(){var e=[];return function t(i){var s={id:i.id,extId:i.extId,type:i.type,name:i.name};i.parent&&(s.parent=i.parent.id),e.push(s);var r=i.children;if(r)for(var o=0,a=r.length;o<a;o++)t(r[o])}(this.rootMetaObject),{id:this.id,projectId:this.projectId,revisionId:this.revisionId,metaObjects:e}}}class MetaObject{constructor(e,t,i,s,r,o,a,n){this.metaModel=e,this.id=t,this.name=i,this.type=s,r&&(this.properties=r),void 0!==o&&null!==o&&(this.parent=o),void 0!==a&&null!==a&&(this.children=a),void 0!==n&&null!==n&&(this.external=n)}getObjectIDsInSubtree(){const e=[];return function t(i){if(!i)return;e.push(i.id);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this),e}withMetaObjectsInSubtree(e){!function t(i){if(!i)return;e(i);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=e[i];const r=[];return function e(i){if(!i)return;t[i.type]&&r.push(i.id);const s=i.children;if(s)for(var o=0,a=s.length;o<a;o++)e(s[o])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class MetaScene{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.metaObjects={},this.metaObjectsByType={},this._typeCounts={},this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}createMetaModel(e,t,i={}){const s=t.projectId||"none",r=t.revisionId||"none",o=t.metaObjects,a=t.author,n=t.createdAt,l=t.creatingApplication,h=t.schema,c=new MetaModel(this,e,s,r,a,n,l,h,null);this.metaModels[e]=c;for(let e=0,t=o.length;e<t;e++){const t=o[e],i=t.type,s=t.id,r=t.name,a=t.properties,n=null,l=null,h=t.external,d=new MetaObject(c,s,r,i,a,n,l,h);this.metaObjects[s]=d,(this.metaObjectsByType[i]||(this.metaObjectsByType[i]={}))[s]=d,void 0===this._typeCounts[i]?this._typeCounts[i]=1:this._typeCounts[i]++}for(let e=0,t=o.length;e<t;e++){const t=o[e],i=t.id,s=this.metaObjects[i];if(s)if(void 0===t.parent||null===t.parent)c.rootMetaObject=s;else if(t.parent){let e=this.metaObjects[t.parent];e&&(s.parent=e,e.children=e.children||[],e.children.push(s))}}return this.fire("metaModelCreated",e),c}destroyMetaModel(e){const t=this.metaModels[e];if(!t)return;const i=this.metaObjects,s=this.metaObjectsByType;let r=e=>{delete i[e.id];const t=s[e.type];t&&t[e.id]&&(delete t[e.id],0==--this._typeCounts[e.type]&&(delete this._typeCounts[e.type],delete s[e.type]));const o=e.children;if(o)for(let e=0,t=o.length;e<t;e++){const t=o[e];r(t)}};r(t.rootMetaObject),delete this.metaModels[e],this.fire("metaModelDestroyed",e)}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,i){const s=[],r=this.metaObjects[e],o=t&&t.length>0?arrayToMap(t):null,a=i&&i.length>0?arrayToMap(i):null;return function e(t){if(!t)return;var i=!0;a&&a[t.type]?i=!1:o&&!o[t.type]&&(i=!1),i&&s.push(t.id);const r=t.children;if(r)for(var n=0,l=r.length;n<l;n++)e(r[n])}(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function arrayToMap(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=!0;return t}class Viewer{constructor(e){this.language="en",this.scene=new Scene({viewer:this,canvasId:e.canvasId,canvasElement:e.canvasElement,webgl2:!1,contextAttr:{preserveDrawingBuffer:!1!==e.preserveDrawingBuffer,premultipliedAlpha:!!e.premultipliedAlpha},spinnerElementId:e.spinnerElementId,transparent:!1!==e.transparent,gammaInput:!0,gammaOutput:!0,clearColorAmbient:e.clearColorAmbient,ticksPerRender:1,ticksPerOcclusionTest:20,units:e.units,scale:e.scale,origin:e.origin,saoEnabled:e.saoEnabled,alphaDepthMask:!1!==e.alphaDepthMask}),this.metaScene=new MetaScene(this,this.scene),this.id=e.id||this.scene.id,this.camera=this.scene.camera,this.cameraFlight=new CameraFlightAnimation(this.scene,{duration:.5}),this.cameraControl=new CameraControl(this.scene,{doublePickFlyTo:!0}),this._plugins=[],this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}log(e){console.log(`[xeokit viewer ${this.id}]: ${e}`)}error(e){console.error(`[xeokit viewer ${this.id}]: ${e}`)}addPlugin(e){this._plugins.push(e)}removePlugin(e){for(let t=0,i=this._plugins.length;t<i;t++){const i=this._plugins[t];if(i===e)return i.clear&&i.clear(),void this._plugins.splice(t,1)}}sendToPlugins(e,t){for(let i=0,s=this._plugins.length;i<s;i++){const s=this._plugins[i];s.send&&s.send(e,t)}}clear(){throw'Viewer#clear() no longer implemented - use \'#sendToPlugins("clear") instead'}resetView(){throw"Viewer#resetView() no longer implemented - use CameraMemento & ObjectsMemento classes instead"}getSnapshot(e={}){this.sendToPlugins("snapshotStarting");const t=void 0!==e.width&&void 0!==e.height,i=this.scene.canvas.canvas,s=i.clientWidth,r=i.clientHeight,o=i.style.width,a=i.style.height,n=e.width?Math.floor(e.width):i.width,l=e.height?Math.floor(e.height):i.height;t&&(i.style.width=n+"px",i.style.height=l+"px"),this.scene.render(!0);const h=this.scene.canvas._getSnapshot(e);return t&&(i.style.width=o,i.style.height=a,i.width=s,i.height=r,this.scene.glRedraw()),this.sendToPlugins("snapshotFinished"),h}destroy(){const e=this._plugins.slice();for(let t=0,i=e.length;t<i;t++){e[t].destroy()}this.scene.destroy()}}const tempVec3$a=math.vec3();class BCFViewpointsPlugin extends Plugin{constructor(e,t={}){super("BCFViewpoints",e,t),this.originatingSystem=t.originatingSystem||"xeokit.io",this.authoringTool=t.authoringTool||"xeokit.io"}getViewpoint(e={}){const t=this.viewer.scene,i=t.camera,s=t.realWorldOffset,r=!0===e.reverseClippingPlanes;let o={},a=math.normalizeVec3(math.subVec3(i.look,i.eye,math.vec3())),n=i.eye,l=i.up;i.yUp&&(a=YToZ(a),n=YToZ(n),l=YToZ(l));const h=xyzArrayToObject(math.addVec3(n,s));"ortho"===i.projection?o.orthogonal_camera={camera_view_point:h,camera_direction:xyzArrayToObject(a),camera_up_vector:xyzArrayToObject(l),view_to_world_scale:i.ortho.scale}:o.perspective_camera={camera_view_point:h,camera_direction:xyzArrayToObject(a),camera_up_vector:xyzArrayToObject(l),field_of_view:i.perspective.fov},o.lines=[],o.bitmaps=[],o.clipping_planes=[];const c=t.sectionPlanes;for(let e in c)if(c.hasOwnProperty(e)){let t,s=c[e],a=s.pos;t=r?math.negateVec3(s.dir,math.vec3()):s.dir,i.yUp&&(a=YToZ(a),t=YToZ(t)),a=xyzArrayToObject(s.pos),t=xyzArrayToObject(t),o.clipping_planes.push({location:a,direction:t})}o.components={visibility:{view_setup_hints:{spaces_visible:!!e.spacesVisible,space_boundaries_visible:!!e.spaceBoundariesVisible,openings_visible:!!e.openingsVisible}}};const d=t.objectIds,u=t.visibleObjects,p=t.visibleObjectIds,m=d.filter(e=>!u[e]),_=t.selectedObjectIds;return e.defaultInvisible||p.length<m.length?(o.components.visibility.exceptions=p.map(e=>this._objectIdToComponent(e)),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=m.map(e=>this._objectIdToComponent(e)),o.components.visibility.default_visibility=!0),o.components.selection=_.map(e=>this._objectIdToComponent(e)),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_objectIdToComponent(e){return{ifc_guid:e,originating_system:this.originatingSystem,authoring_tool_id:this.authoringTool}}setViewpoint(e,t={}){if(!e)return;const i=this.viewer,s=i.scene,r=s.camera,o=!1!==t.rayCast,a=!1!==t.immediate,n=!1!==t.reset,l=s.realWorldOffset,h=!0===t.reverseClippingPlanes;if(s.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.forEach(function(e){let t=xyzObjectToArray(e.location,tempVec3$a),i=xyzObjectToArray(e.direction,tempVec3$a);h&&math.negateVec3(i),r.yUp&&(t=ZToY(t),i=ZToY(i)),new SectionPlane(s,{pos:t,dir:i})}),n&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach(e=>s.setObjectsVisible(e.ifc_guid,!1))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach(e=>s.setObjectsVisible(e.ifc_guid,!0)));const t=e.components.visibility.view_setup_hints;t&&(!1===t.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===t.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!1),t.space_boundaries_visible)}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),Object.keys(s.models).forEach(()=>{e.components.selection.forEach(e=>s.setObjectsSelected(e.ifc_guid,!0))}))}if(e.perspective_camera||e.orthogonal_camera){let n,h,c,d;if(e.perspective_camera?(n=xyzObjectToArray(e.perspective_camera.camera_view_point,tempVec3$a),h=xyzObjectToArray(e.perspective_camera.camera_direction,tempVec3$a),c=xyzObjectToArray(e.perspective_camera.camera_up_vector,tempVec3$a),r.perspective.fov=e.perspective_camera.field_of_view,d="perspective"):(n=xyzObjectToArray(e.orthogonal_camera.camera_view_point,tempVec3$a),h=xyzObjectToArray(e.orthogonal_camera.camera_direction,tempVec3$a),c=xyzObjectToArray(e.orthogonal_camera.camera_up_vector,tempVec3$a),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,d="ortho"),math.subVec4(n,l),r.yUp&&(n=ZToY(n),h=ZToY(h),c=ZToY(c)),o){const e=s.pick({pickSurface:!0,origin:n,direction:h});h=e?e.worldPos:math.addVec3(n,h,tempVec3$a)}else h=math.addVec3(n,h,tempVec3$a);a?(r.eye=n,r.look=h,r.up=c,r.projection=d):i.cameraFlight.flyTo({eye:n,look:h,up:c,duration:t.duration,projection:d})}}destroy(){super.destroy()}}function xyzArrayToObject(e){return{x:e[0],y:e[1],z:e[2]}}function xyzObjectToArray(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function YToZ(e){return new Float64Array([e[0],-e[2],e[1]])}function ZToY(e){return new Float64Array([e[0],e[2],-e[1]])}const tempVec3a$5=math.vec3();class ThreeDMode extends Controller{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._buttonElement=t.buttonElement,this._cameraControlNavModeMediator=t.cameraControlNavModeMediator,this._active=!1,this.on("enabled",e=>{e?this._buttonElement.classList.remove("disabled"):this._buttonElement.classList.add("disabled")}),this._buttonElement.addEventListener("click",e=>{this.setActive(!this.getActive(),()=>{}),e.preventDefault()}),this.bimViewer.on("reset",()=>{this.setActive(!0,()=>{})})}setActive(e,t){this._active!==e?(this._active=e,e?(this._buttonElement.classList.add("active"),t?this._enterThreeDMode(()=>{this.fire("active",this._active),t()}):(this._enterThreeDMode(),this.fire("active",this._active))):(this._buttonElement.classList.remove("active"),t?this._exitThreeDMode(()=>{this.fire("active",this._active),t()}):(this._exitThreeDMode(),this.fire("active",this._active)))):t&&t()}_enterThreeDMode(e){const t=this.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds),r=math.getAABB3Diag(s),o=math.getAABB3Center(s,tempVec3a$5),a=Math.abs(r/Math.tan(32.5)),n=i.camera,l=n.yUp?[-1,-1,-1]:[1,1,1],h=n.yUp?[-1,1,-1]:[-1,1,1];t.cameraControl.pivotPos=o,this.bimViewer._navCubeMode.setActive(!0),this.bimViewer._firstPersonMode.setEnabled(!0),this._cameraControlNavModeMediator.setThreeDModeActive(!0),this.bimViewer._sectionTool.setEnabled(!0),e?t.cameraFlight.flyTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r,projection:"perspective",duration:1},()=>{e()}):t.cameraFlight.jumpTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r,projection:"perspective"})}_exitThreeDMode(e){const t=this.viewer,i=t.scene,s=i.camera,r=i.getAABB(i.visibleObjectIds),o=math.getAABB3Center(r),a=math.getAABB3Diag(r),n=Math.abs(a/Math.tan(45*math.DEGTORAD)),l=1.3*a,h=tempVec3a$5;h[0]=o[0]+s.worldUp[0]*n,h[1]=o[1]+s.worldUp[1]*n,h[2]=o[2]+s.worldUp[2]*n;const c=math.mulVec3Scalar(s.worldForward,-1,[]);this.bimViewer._sectionTool.setActive(!1),this.bimViewer._sectionTool.clear(),this.bimViewer._firstPersonMode.setEnabled(!1),this.bimViewer._sectionTool.setEnabled(!1),this._cameraControlNavModeMediator.setThreeDModeActive(!1),e?t.cameraFlight.flyTo({projection:"ortho",eye:h,look:o,up:c,orthoScale:l},()=>{this.bimViewer._navCubeMode.setActive(!1)}):(t.cameraFlight.jumpTo({projection:"ortho",eye:h,look:o,up:c,orthoScale:l}),this.bimViewer._navCubeMode.setActive(!1))}}class ObjectContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity;t.cameraFlight.flyTo({aabb:s.aabb,duration:.5},()=>{setTimeout(function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)},500)}),t.cameraControl.pivotPos=math.getAABB3Center(s.aabb)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}},{title:"Show in Tree",doAction:function(e){const t=e.entity.id;e.showObjectInExplorers(t)}}],[{title:"Hide",getEnabled:function(e){return e.entity.visible},doAction:function(e){e.entity.visible=!1}},{title:"Hide Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.visibleObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),r.withMetaObjectsInSubtree(e=>{const t=i.objects[e.id];t&&(t.visible=!0)}))}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects<t.numObjects||e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",getEnabled:function(e){return!e.entity.xrayed},doAction:function(e){const t=e.entity;t.xrayed=!0,t.pickable=!1}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.objectIds,!0),i.setObjectsXRayed(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),r.withMetaObjectsInSubtree(e=>{const t=i.objects[e.id];t&&(t.xrayed=!1,t.pickable=!0)}))}},{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects<t.numObjects},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1),t.setObjectsXRayed(t.objectIds,!0)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",getEnabled:function(e){return!e.entity.selected},doAction:function(e){e.entity.selected=!0}},{title:"Undo Select",getEnabled:function(e){return e.entity.selected},doAction:function(e){e.entity.selected=!1}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class CanvasContextMenu extends ContextMenu{constructor(e={}){super({context:e.context,items:[[{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show all",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects<t.numObjects||e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=math.getAABB3Center(s)}}],[{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects<t.numObjects},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene.xrayedObjectIds;e.viewer.scene.setObjectsPickable(t,!0),e.viewer.scene.setObjectsXRayed(t,!1)}}],[{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Reset View",doAction:function(e){e.bimViewer.resetView()}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}const explorerTemplate='<div class="xeokit-tabs">\n    <div class="xeokit-tab xeokit-modelsTab">\n        <a class="xeokit-tab-btn" href="#">Models</a>\n        <div class="xeokit-tab-content">\n            <div class="xeokit-btn-group">\n                <button type="button" class="xeokit-unloadAllModels xeokit-btn disabled" data-tippy-content="Unload all models">Unload all</button>\n            </div>\n            <div class="xeokit-models" ></div>\n        </div>\n    </div>\n    <div class="xeokit-tab xeokit-objectsTab">\n        <a class="xeokit-tab-btn disabled" href="#">Objects</a>\n        <div class="xeokit-tab-content">\n         <div class="xeokit-btn-group">\n            <button type="button" class="xeokit-showAllObjects xeokit-btn disabled" data-tippy-content="Show all objects">Show all</button>\n            <button type="button" class="xeokit-hideAllObjects xeokit-btn disabled" data-tippy-content="Hide all objects">Hide all</button>\n        </div>\n        <div class="xeokit-objects xeokit-tree-panel" ></div>\n        </div>\n    </div>\n    <div class="xeokit-tab xeokit-classesTab">\n        <a class="xeokit-tab-btn disabled" href="#">Classes</a>\n        <div class="xeokit-tab-content">\n            <div class="xeokit-btn-group">\n                <button type="button" class="xeokit-showAllClasses xeokit-btn disabled" data-tippy-content="Show all classes">Show all</button>\n                <button type="button" class="xeokit-hideAllClasses xeokit-btn disabled" data-tippy-content="Hide all classes">Hide all</button>\n            </div>\n            <div class="xeokit-classes xeokit-tree-panel" ></div>\n        </div>\n    </div>\n     <div class="xeokit-tab xeokit-storeysTab">\n        <a class="xeokit-tab-btn disabled" href="#">Storeys</a>\n        <div class="xeokit-tab-content">\n         <div class="xeokit-btn-group">\n                <button type="button" class="xeokit-showAllStoreys xeokit-btn disabled" data-tippy-content="Show all storeys">Show all</button>\n                <button type="button" class="xeokit-hideAllStoreys xeokit-btn disabled" data-tippy-content="Hide all storeys">Hide all</button>\n            </div>\n             <div class="xeokit-storeys xeokit-tree-panel"></div>\n        </div>\n    </div>\n</div>',toolbarTemplate='<div class="xeokit-toolbar">\n    \x3c!-- Reset button --\x3e\n    <div class="xeokit-btn-group">\n        <button type="button" class="xeokit-reset xeokit-btn fa fa-home fa-2x disabled" data-tippy-content="Reset view"></button>\n    </div>\n    \x3c!-- 3D Mode button --\x3e\n    <div class="xeokit-btn-group" role="group">\n        <button type="button" class="xeokit-threeD xeokit-btn fa fa-cube fa-2x" data-tippy-content="Toggle 2D/3D"></button>\n    </div>\n    \x3c!-- Fit button --\x3e\n    <div class="xeokit-btn-group" role="group">\n        <button type="button" class="xeokit-fit xeokit-btn fa fa-crop fa-2x disabled" data-tippy-content="View fit"></button>\n    </div>\n    \x3c!-- First Person mode button --\x3e\n    <div class="xeokit-btn-group" role="group">\n        <button type="button" class="xeokit-firstPerson xeokit-btn fa fa-male fa-2x disabled" data-tippy-content="First person"></button>\n    </div>\n    \x3c!-- Tools button group --\x3e\n    <div class="xeokit-btn-group" role="group">\n        \x3c!-- Hide tool button --\x3e\n        <button type="button" class="xeokit-hide xeokit-btn fa fa-eraser fa-2x disabled" data-tippy-content="Hide objects"></button>\n        \x3c!-- Select tool button --\x3e\n        <button type="button" class="xeokit-select xeokit-btn fa fa-mouse-pointer fa-2x disabled" data-tippy-content="Select objects"></button>\n        \x3c!-- Query tool button --\x3e\n        <button type="button" class="xeokit-query xeokit-btn fa fa-info-circle fa-2x disabled" data-tippy-content="Query objects"></button>\n        \x3c!-- section tool button --\x3e\n        <button type="button" class="xeokit-section xeokit-btn fa fa-cut fa-2x disabled" data-tippy-content="Slice objects"><div class="xeokit-section-counter"></div></button>\n    </div>\n\n</div>';function initTabs(e){const t="xeokit-tab",i="active";function s(e){let s=e.parentNode.querySelectorAll("."+t);for(let t=0;t<s.length;t++){let r=s[t];r.isEqualNode(e)?r.classList.add(i):r.classList.remove(i)}}let r=e.querySelectorAll(".xeokit-tabs");for(let e=0;e<r.length;e++){let i=r[e].querySelectorAll("."+t);s(i[0]);for(let e=0;e<i.length;e++){i[e].querySelector(".xeokit-tab-btn").addEventListener("click",function(e){e.preventDefault(),this.classList.contains("disabled")||s(e.target.parentNode)})}}}class BIMViewer extends Controller{constructor(e,t={}){if(!t.canvasElement)throw"Config expected: canvasElement";if(!t.explorerElement)throw"Config expected: explorerElement";if(!t.toolbarElement)throw"Config expected: toolbarElement";if(!t.navCubeCanvasElement)throw"Config expected: navCubeCanvasElement";const i=t.canvasElement,s=t.explorerElement,r=t.toolbarElement,o=t.navCubeCanvasElement,a=t.queryInfoPanelElement,n=t.busyModelBackdropElement;s.oncontextmenu=(e=>{e.preventDefault()}),r.oncontextmenu=(e=>{e.preventDefault()}),o.oncontextmenu=(e=>{e.preventDefault()});const l=new Viewer({canvasElement:i,transparent:!0});super(null,t,e,l),this._configs={},this.viewer=l,this._customizeViewer(),this._initCanvasContextMenus(),this._initConfigs(),s.innerHTML=explorerTemplate,r.innerHTML=toolbarTemplate,this._explorerElement=s,initTabs(s),this._modelsExplorer=new ModelsExplorer(this,{modelsTabElement:s.querySelector(".xeokit-modelsTab"),unloadModelsButtonElement:s.querySelector(".xeokit-unloadAllModels"),modelsElement:s.querySelector(".xeokit-models")}),this._objectsExplorer=new ObjectsExplorer(this,{objectsTabElement:s.querySelector(".xeokit-objectsTab"),showAllObjectsButtonElement:s.querySelector(".xeokit-showAllObjects"),hideAllObjectsButtonElement:s.querySelector(".xeokit-hideAllObjects"),objectsElement:s.querySelector(".xeokit-objects")}),this._classesExplorer=new ClassesExplorer(this,{classesTabElement:s.querySelector(".xeokit-classesTab"),showAllClassesButtonElement:s.querySelector(".xeokit-showAllClasses"),hideAllClassesButtonElement:s.querySelector(".xeokit-hideAllClasses"),classesElement:s.querySelector(".xeokit-classes")}),this._storeysExplorer=new StoreysExplorer(this,{storeysTabElement:s.querySelector(".xeokit-storeysTab"),showAllStoreysButtonElement:s.querySelector(".xeokit-showAllStoreys"),hideAllStoreysButtonElement:s.querySelector(".xeokit-hideAllStoreys"),storeysElement:s.querySelector(".xeokit-storeys")}),this._resetAction=new ResetAction(this,{buttonElement:r.querySelector(".xeokit-reset"),active:!1}),this._fitAction=new FitAction(this,{buttonElement:r.querySelector(".xeokit-fit"),active:!1});const h=new function(e){let t=!1;this.setThreeDModeActive=(i=>{i?(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="orbit",e.viewer.cameraControl.followPointer=!0):(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="planView",e.viewer.cameraControl.followPointer=!1),t=i}),this.setFirstPersonModeActive=(i=>{e.viewer.cameraControl.navMode=i?"firstPerson":t?"orbit":"planView",e.viewer.cameraControl.followPointer="planView"!==e.viewer.cameraControl.navMode})}(this);this._threeDMode=new ThreeDMode(this,{buttonElement:r.querySelector(".xeokit-threeD"),cameraControlNavModeMediator:h,active:!1}),this._firstPersonMode=new FirstPersonMode(this,{buttonElement:r.querySelector(".xeokit-firstPerson"),cameraControlNavModeMediator:h,active:!1}),this._hideTool=new HideTool(this,{buttonElement:r.querySelector(".xeokit-hide"),active:!1}),this._selectionTool=new SelectionTool(this,{buttonElement:r.querySelector(".xeokit-select"),active:!1}),this._queryTool=new QueryTool(this,{buttonElement:r.querySelector(".xeokit-query"),queryInfoPanelElement:a,active:!1}),this._sectionTool=new SectionTool(this,{buttonElement:r.querySelector(".xeokit-section"),counterElement:r.querySelector(".xeokit-section-counter"),active:!1}),this._navCubeMode=new NavCubeMode(this,{navCubeCanvasElement:o,active:!0}),this._busyModal=new BusyModal(this,{busyModalBackdropElement:n}),this._threeDMode.setActive(!0),this._firstPersonMode.setActive(!1),this._navCubeMode.setActive(!0),this._modelsExplorer.on("modelLoaded",e=>{1===this._modelsExplorer.getNumModelsLoaded()&&this.setControlsEnabled(!0),this.fire("modelLoaded",e)}),this._modelsExplorer.on("modelUnloaded",e=>{0===this._modelsExplorer.getNumModelsLoaded()&&(this.setControlsEnabled(!1),this.openTab("models")),this.fire("modelUnloaded",e)}),this._queryTool.on("queryPicked",e=>{this.fire("queryPicked",e)}),this._queryTool.on("queryNotPicked",()=>{this.fire("queryNotPicked",!0)}),this._resetAction.on("reset",()=>{this.fire("reset",!0)}),this._mutexActivation([this._queryTool,this._hideTool,this._selectionTool,this._sectionTool]),s.querySelector(".xeokit-showAllObjects").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllObjects").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-showAllClasses").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllClasses").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-showAllStoreys").addEventListener("click",e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()}),s.querySelector(".xeokit-hideAllStoreys").addEventListener("click",e=>{this.setAllObjectsVisible(!1),e.preventDefault()}),s.querySelector(".xeokit-unloadAllModels").addEventListener("click",e=>{this.setControlsEnabled(!1),this._modelsExplorer.unloadAllModels(),e.preventDefault()}),this._bcfViewpointsPlugin=new BCFViewpointsPlugin(this.viewer,{})}_customizeViewer(){const e=this.viewer.scene;e.xrayMaterial.fill=!1,e.xrayMaterial.fillAlpha=.1,e.xrayMaterial.fillColor=[0,0,0],e.xrayMaterial.edges=!0,e.xrayMaterial.edgeAlpha=.3,e.xrayMaterial.edgeColor=[0,0,0],e.highlightMaterial.edges=!0,e.highlightMaterial.edgeColor=[.5,.5,0],e.highlightMaterial.edgeAlpha=.9,e.highlightMaterial.fill=!0,e.highlightMaterial.fillAlpha=.1,e.highlightMaterial.fillColor=[1,0,0],e.clearLights(),new AmbientLight(e,{color:[.3,.3,.3],intensity:1}),new DirLight(e,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"world"}),new DirLight(e,{dir:[-.8,-.4,.4],color:[1,1,1],intensity:1,space:"world"}),new DirLight(e,{dir:[.2,-.8,.8],color:[.6,.6,.6],intensity:1,space:"world"}),this.viewer.cameraControl.panRightClick=!0,this.viewer.cameraControl.followPointer=!0,this.viewer.cameraControl.doublePickFlyTo=!0,this.viewer.cameraControl.dollyRate=20,this.viewer.cameraControl.dollyInertia=.7;const t=document.createRange().createContextualFragment("<div class='xeokit-camera-pivot-marker'></div>").firstChild;document.body.appendChild(t),this.viewer.cameraControl.pivotElement=t,e.camera.perspective.near=.05,e.camera.perspective.far=3e3,e.camera.ortho.near=.05,e.camera.ortho.far=3e3;const i=e.sao;i.enabled=!1,i.bias=.5,i.intensity=.5,i.scale=1200,i.kernelRadius=100;var s=200,r=!1;e.camera.on("matrix",()=>{if(this._configs.saoInteractive)return;const t=this._configs.saoInteractiveDelay;s=null!==t&&void 0!==t?this._configs.saoInteractiveDelay:200,r&&(e.sao.enabled=!1,r=!1)}),e.on("tick",t=>{this._configs.saoInteractive?r||(e.sao.enabled=!!this._configs.saoEnabled,r=!0):r||(s-=t.deltaTime)<=0&&(r||(e.sao.enabled=!!this._configs.saoEnabled,r=!0))})}_initCanvasContextMenus(){this._canvasContextMenu=new CanvasContextMenu,this._objectContextMenu=new ObjectContextMenu,this.viewer.cameraControl.on("rightClick",e=>{const t=e.event,i=this.viewer.scene.pick({canvasPos:[t.offsetX,t.offsetY]});i&&i.entity.isObject?(this._canvasContextMenu.hide(),this._objectContextMenu.context={viewer:this.viewer,bimViewer:this,showObjectInExplorers:e=>{const t=this.getOpenTab();"objects"!==t&&"classes"!==t&&"storeys"!==t&&this.openTab("objects"),this.showObjectInExplorers(e)},entity:i.entity},this._objectContextMenu.show(t.pageX,t.pageY)):(this._objectContextMenu.hide(),this._canvasContextMenu.context={viewer:this.viewer,bimViewer:this},this._canvasContextMenu.show(t.pageX,t.pageY))})}_initConfigs(){this.setConfigs({cameraNear:"0.05",cameraFar:"3000.0",saoEnabled:"false",saoBias:"0.5",saoIntensity:"0.5",saoScale:"1200.0",saoKernelRadius:"100",xrayContext:!0,backgroundColor:[1,1,1],saoInteractive:!0,saoInteractiveDelay:200,objectColorSource:"model"})}setConfigs(e){for(let t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setConfig(t,i)}}setConfig(e,t){function i(e){return!0===e||"true"===e}try{switch(e){case"backgroundColor":const r=t;this.setBackgroundColor(r),this._configs[e]=r;break;case"cameraNear":const o=parseFloat(t);this.viewer.scene.camera.perspective.near=o,this.viewer.scene.camera.ortho.near=o,this._configs[e]=o;break;case"cameraFar":const a=parseFloat(t);this.viewer.scene.camera.perspective.far=a,this.viewer.scene.camera.ortho.far=a,this._configs[e]=a;break;case"saoEnabled":this.viewer.scene.sao.enabled=this._configs[e]=i(t);break;case"saoBias":this.viewer.scene.sao.bias=parseFloat(t);break;case"saoIntensity":this.viewer.scene.sao.intensity=parseFloat(t);break;case"saoScale":this.viewer.scene.sao.scale=this._configs[e]=parseFloat(t);break;case"saoKernelRadius":this.viewer.scene.sao.kernelRadius=this._configs[e]=parseFloat(t);break;case"saoBlur":this.viewer.scene.sao.blur=this._configs[e]=i(t);break;case"viewFitFOV":this.viewer.cameraFlight.fitFOV=this._configs[e]=parseFloat(t);break;case"viewFitDuration":this.viewer.cameraFlight.duration=this._configs[e]=parseFloat(t);break;case"perspectiveFOV":this.viewer.camera.perspective.fov=this._configs[e]=parseFloat(t);break;case"excludeUnclassifiedObjects":this._configs[e]=i(t);break;case"objectColorSource":this.setObjectColorSource(t),this._configs[e]=t;break;case"xrayContext":this._configs[e]=t;break;case"saoInteractive":this._configs.saoInteractive=i(t);break;case"saoInteractiveDelay":var s=parseFloat(t);s<0&&(this.error("setConfig() - saoInteractiveDelay cannot be less than zero - clamping to zero"),s=0),this._configs.saoInteractiveDelay=parseFloat(t);break;default:this.error("setConfig() - unsupported configuration: '"+e+"'")}}catch(t){this.error("setConfig() - failed to configure '"+e+"': "+t)}}getConfig(e){return this._configs[e]}getProjectsInfo(e,t){e?this.server.getProjects(e,e=>{this.error("getProjectsInfo() - "+e),t&&t(e)}):this.error("getProjectsInfo() - Argument expected: 'done'")}getProjectInfo(e,t,i){e?t?this.server.getProject(e,t,e=>{this.error("getProjectInfo() - "+e),i&&i(e)}):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getProjectInfo() - Argument expected: projectId")}getObjectInfo(e,t,i,s,r){e?t?i?s?this.server.getObjectInfo(e,t,i,s,e=>{r&&r(e)}):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getObjectInfo() - Argument expected: objectId"):this.error("getObjectInfo() - Argument expected: modelId"):this.error("getObjectInfo() - Argument expected: projectId")}loadProject(e,t,i){e?this._modelsExplorer.loadProject(e,()=>{t&&t()},e=>{this.error("loadProject() - "+e),i&&i(e)}):this.error("loadProject() - Argument expected: objectId")}unloadProject(){this._modelsExplorer.unloadProject(),this.openTab("models"),this.setControlsEnabled(!1)}getLoadedProjectId(){return this._modelsExplorer.getLoadedProjectId()}getModelIds(){return this._modelsExplorer.getModelIds()}loadModel(e,t,i){e?this._modelsExplorer.loadModel(e,()=>{t&&t()},e=>{this.error("loadModel() - "+e),i&&i(e)}):this.error("loadModel() - Argument expected: modelId")}loadAllModels(e=function(){}){const t=this._modelsExplorer.getModelIds(),i=(e,s)=>{if(e>=t.length)s();else{const r=t[e];this._modelsExplorer.isModelLoaded(r)?i(e+1,s):this._modelsExplorer.loadModel(r,()=>{i(e+1,s)},t=>{this.error("loadAllModels() - "+t),i(e+1,s)})}};i(0,e)}getLoadedModelIds(){return this._modelsExplorer._getLoadedModelIds()}isModelLoaded(e){if(e)return this._modelsExplorer.isModelLoaded(e);this.error("unloadModel() - Argument expected: modelId")}unloadModel(e){e?this._modelsExplorer.unloadModel(e):this.error("unloadModel() - Argument expected: modelId")}unloadAllModels(){this._modelsExplorer.unloadAllModels()}setBackgroundColor(e){this.viewer.scene.canvas.canvas.style.background="rgba("+255*e[0]+","+255*e[1]+","+255*e[2]+", 1.0)"}setObjectColorSource(e){switch(e){case"model":case"viewer":break;default:return e="model",void this.error("setObjectColorSource() - Unsupported value - accepted values are 'model' and 'viewer' - defaulting to 'model'")}this._objectColorSource=e}getObjectColorSource(){return this._objectColorSource||"model"}setViewerState(e,t=(()=>{})){e.tabOpen&&this.openTab(e.tabOpen),e.expandObjectsTree&&this._objectsExplorer.expandTreeViewToDepth(e.expandObjectsTree),e.expandClassesTree&&this._classesExplorer.expandTreeViewToDepth(e.expandClassesTree),e.expandStoreysTree&&this._storeysExplorer.expandTreeViewToDepth(e.expandStoreysTree),e.setCamera&&this.setCamera(e.setCamera),this._parseSelectedStorey(e,()=>{this._parseThreeDMode(e,()=>{t()})})}_parseSelectedStorey(e,t){e.selectedStorey?(this.selectStorey(e.selectedStorey),t()):t()}_parseThreeDMode(e,t){const i=!1!==e.threeDActive;this.set3DEnabled(i,t)}showObjectInExplorers(e){e?(this._objectsExplorer.showNodeInTreeView(e),this._classesExplorer.showNodeInTreeView(e),this._storeysExplorer.showNodeInTreeView(e)):this.error("showObjectInExplorers() - Argument expected: objectId")}unShowObjectInExplorers(){this._objectsExplorer.unShowNodeInTreeView(),this._classesExplorer.unShowNodeInTreeView(),this._storeysExplorer.unShowNodeInTreeView()}setObjectsVisible(e,t){this._withObjectsInSubtree(e,e=>{e.visible=t})}setAllObjectsVisible(e){e?this.viewer.scene.setObjectsVisible(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsVisible(this.viewer.scene.visibleObjectIds,!1)}setObjectsXRayed(e,t){this._withObjectsInSubtree(e,e=>{e.xrayed=t})}setAllObjectsXRayed(e){e?this.viewer.scene.setObjectsXRayed(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsXRayed(this.viewer.scene.xrayedObjectIds,!1)}setObjectsSelected(e,t){this._withObjectsInSubtree(e,e=>{e.selected=t})}setAllObjectsSelected(e){e?this.viewer.scene.setObjectsSelected(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsSelected(this.viewer.scene.selectedObjectIds,!1)}_withObjectsInSubtree(e,t){if(e)for(let i=0,s=e.length;i<s;i++){const s=e[i];this.viewer.metaScene.withMetaObjectsInSubtree(s,e=>{const i=this.viewer.scene.objects[e.id];i&&t(i)})}else this.error("Argument expected: objectIds")}flyToObject(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectId");const i=this.viewer,s=i.scene,r=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,e=>{s.objects[e.id]&&r.push(e.id)}),0===r.length)return this.error("Object not found in viewer: '"+e+"'"),void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const o=s.getAABB(r);i.cameraFlight.flyTo({aabb:o},()=>{t&&t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}),i.cameraControl.pivotPos=math.getAABB3Center(o)}viewFitObjects(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectIds");const i=this.viewer,s=i.scene,r=[];for(var o=0,a=e.length;o<a;o++){const t=e[o];this.viewer.metaScene.withMetaObjectsInSubtree(t,e=>{s.objects[e.id]&&r.push(e.id)})}if(0===r.length)return void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const n=s.getAABB(r);i.cameraFlight.flyTo({aabb:n},()=>{t&&t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}),i.cameraControl.pivotPos=math.getAABB3Center(n)}viewFitAll(e){const t=this.viewer,i=t.scene.getAABB();t.cameraFlight.flyTo({aabb:i},()=>{e&&e()}),t.cameraControl.pivotPos=math.getAABB3Center(i)}jumpToObject(e){if(!e)return void this.error("jumpToObject() - Argument expected: objectId");const t=this.viewer,i=t.scene,s=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,e=>{i.objects[e.id]&&s.push(e.id)}),0===s.length)return void this.error("Object not found in viewer: '"+e+"'");i.setObjectsVisible(s,!0);const r=i.getAABB(s);t.cameraFlight.jumpTo({aabb:r}),t.cameraControl.pivotPos=math.getAABB3Center(r)}setCamera(e){const t=this.viewer.scene.camera;e.eye&&(t.eye=e.eye),e.look&&(t.look=e.look),e.up&&(t.up=e.up)}viewFitModels(e,t){if(!e)return void this.error("viewFitModels() - Argument expected: modelIds");const i=this.viewer,s=i.scene,r=math.AABB3();math.collapseAABB3(r);for(var o=0,a=e.length;o<a;o++){const t=e[o],i=s.models[t];i?(i.visible=!0,i.highlighted=!0,math.expandAABB3(r,i.aabb)):this.error("Model not found in viewer: '"+t+"'")}t?i.cameraFlight.flyTo({aabb:r},()=>{t(),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)}):(i.cameraFlight.jumpTo({aabb:r}),setTimeout(function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)},500)),i.cameraControl.pivotPos=math.getAABB3Center(r)}openTab(e){if(!e)return void this.error("openTab() - Argument expected: tabId");let t;switch(e){case"models":t="xeokit-modelsTab";break;case"objects":t="xeokit-objectsTab";break;case"classes":t="xeokit-classesTab";break;case"storeys":t="xeokit-storeysTab";break;default:return void this.error("openTab() - tab not recognized: '"+e+"'")}let i=this._explorerElement.querySelectorAll(".xeokit-tab"),s=this._explorerElement.querySelector("."+t);for(let e=0;e<i.length;e++){let t=i[e];t.isEqualNode(s)?t.classList.add("active"):t.classList.remove("active")}}getOpenTab(){function e(e,t){return!!e&&(" "+e.className+" ").indexOf(" "+t+" ")>-1}return e(this._explorerElement.querySelector(".xeokit-modelsTab"),"active")?"models":e(this._explorerElement.querySelector(".xeokit-objectsTab"),"active")?"objects":e(this._explorerElement.querySelector(".xeokit-classesTab"),"active")?"classes":e(this._explorerElement.querySelector(".xeokit-storeysTab"),"active")?"storeys":"none"}set3DEnabled(e,t){e?this._threeDMode.setActive(!0,t):this._threeDMode.setActive(!1,t)}get3DEnabled(){return this._threeDMode.getActive()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];i?"IfcBuildingStorey"===i.type?this._storeysExplorer.selectStorey(e,t):this.error("selectStorey() - Object is not an IfcBuildingStorey: '"+e+"'"):this.error("selectStorey() - Object is not found: '"+e+"'")}saveBCFViewpoint(e){return this._bcfViewpointsPlugin.getViewpoint(e)}loadBCFViewpoint(e,t){e?this._bcfViewpointsPlugin.setViewpoint(e,t):this.error("loadBCFViewpoint() - Argument expected: bcfViewpoint")}resetView(){this._resetAction.reset()}setControlsEnabled(e){this._objectsExplorer.setEnabled(e),this._classesExplorer.setEnabled(e),this._storeysExplorer.setEnabled(e),this._resetAction.setEnabled(e),this._fitAction.setEnabled(e),this._threeDMode.setEnabled(e),this._firstPersonMode.setEnabled(e),this._queryTool.setEnabled(e),this._hideTool.setEnabled(e),this._selectionTool.setEnabled(e),this._sectionTool.setEnabled(e)}setKeyboardEnabled(e){this.viewer.scene.input.keyboardEnabled=e}getKeyboardEnabled(){return this.viewer.scene.input.keyboardEnabled}clearSections(){this._sectionTool.clear()}getNumSections(){return this._sectionTool.getNumSections()}destroy(){this.viewer.destroy(),this._bcfViewpointsPlugin.destroy(),this._canvasContextMenu.destroy(),this._objectContextMenu.destroy()}}export{BIMViewer,Server};
